I have an IEnumerable collection of classes, and a second IEnumerable collection, containing a function that returns the same. For example:
IEnumerable<MyClass1> list1;
IEnumerable<MyClass2> list2;
MyClass2 contains an internal collection of MyClass1, and has a function as follows:
Public MyClass2
{
private IEnumerable<MyClass1> internalCollection;
public IEnumerable<MyClass1> ReturnDuplicates(IEnumerable<MyClass1> duplicates
{
return internalCollection.Where(l => duplicates.Select(d => d.ID).ToString() == l.ID.ToString());
}
...
}
I then have a function to compare the two:
// Function to return a flag indicating if the two lists contain
// any of the same data
public bool CheckDuplicates(IEnumerable<MyClass1> col1, IEnumerable<MyClass2> col2)
{
// The following check is wrong as it returns null
IEnumerable<MyClass1> dupe =
col2.Where(w => w.ReturnDuplicates(col1).Count() != 0)
as IEnumerable<MyClass1>;
return (dupe.Count() != 0);
}
The above statement in CheckDuplicates() returns null. However, in the immediate window:
col2.First().ReturnDuplicates(col1).Count()
Returns 1
I think I know the cause of the problem – the statement is returning
IEnumerable<MyClass2>
so is this kind of check possible without a foreach statement?
Why are you casting as
IEnumerable<MyClass1>? The type of dupe seems to beIEnumerable<MyClass2>. That’s why your variable isnull.You may try the following code :
.Any()avoids the complete enumeration needed by.Count(). It will stop enumeration as soon as a match is found.