Child Index within parent via LINQ

Child Index within parent via LINQ

Old forum URL: forums.lhotka.net/forums/t/10775.aspx


TScorpio posted on Friday, October 14, 2011

We're using CSLA 4 with VB 2010. We have a function in the parent object that searches a child list for a supplied GUID and returns its index number.

Currenty we're using a for loop to interate through all the children until we find the right one. Once found we return it's index number. We would like to replace that with LINQ, but we're not sure how to set it up.

Here is what I've got, but it always fails on the me.IndexOf part.

 

 

 

 

 

Dim i = From FTPInfo As FTPConfigInfo In Me Where FTPInfo.FtpConfigGuid = childGuid Select FTPInfo
Dim childIndex As Integer = IIf(Not (i Is Nothing), Me.IndexOf(i), -1)
Return childIndex

The error is:
Unable to cast object of type 'WhereSelectEnumerableIterator`2[FTPConfigInfo,FTPConfigInfo]' to type 'FTPConfigInfo'.

What am I doing wrong?

JonnyBee replied on Saturday, October 15, 2011

A Linq Select statement will always return an IEnumerable.

What you need to use here is the FirstOrDefault statement and probably in a mixed mode (both fluent and verbose syntax):
Dim i = (From FTPInfo As FTPConfigInfo In Me Where FTPInfo.FtpConfigGuid = childGuid Select FTPInfo).FirstOrDefault()

will return the first "row" or null.

TScorpio replied on Thursday, October 20, 2011

I would have never thought about appending FirstOrDefault to cast the result as an object. Very nice!!!!!

two last follow up questions:

#1: After using LinQ to assign i, I'm using Me.IndexOf(i) to get it's index number in the collection. I’m wondering if the IndexOf has to do the same type of search again? If that's the case, is there a way to combine the LinQ and IndexOf into a single step so the child index number can be found with only one pass through the collection.

#2: I was going to create an Index on my child property to speed up the LinQ searching, but I can't get VB to ever regonize the Indexable keyword. It doesn't show up in the intellisence or a search through the namespaces. How do you enable it? We're using VB.NET 2010 & CSLA 4.0

 

JonnyBee replied on Thursday, October 20, 2011

#1:

Dim i = (From FTPInfo As FTPConfigInfo In Me Where FTPInfo.FtpConfigGuid = childGuid Select FTPInfo).First().Position

should work but you must catch Exception if Item is not in list.

#2 Csla 4.x has no built in indexing. Look at other 3rd party libraries for indexing, ex: http://i4o.codeplex.com and I'm sure there are others as well.

 

Copyright (c) Marimer LLC