Intersection of two collections of data (Lists)

c# entity entity-framework intersection linq

Question

I have two sets of data (Lists of complex objects or SQL data - LINQ to Entities) where im trying to find the intersection of the two sets of data. Specifically an intersection of the Complex property, "HashData" as seen below:

SQL data

The set on the left is likely to be about 10000 rows, whilst the set on the right is always a subset of about 100 rows. I realise that if i sort the set on the left by "Hashdata" when storing it, doing a search would be a whole lot quicker using some sort of Binary search algorithm, however i cannot do this for reasons not pertinent to the question.

The smaller subset of data is never stored in SQL (only showed in a SQL table below for explanatory purposes). It is presented in a List<ShowData> at runtime.

At the moment i'm doing a pathetic loop through the data and matching like this (where recording is the 100 row List and ShowData is the 10000 row List):

List<ShowData> ShowData = (from showData in context.ShowDatas
                           where (showData.Show.Id == advert.Id)
                           orderby showData.HashData ascending
                           select showData).ToList();

foreach (ShowData recording in recordingPoints) {
    foreach (ShowData actual in ShowData) {
        if (recording.HashData == actual.HashData) {
        }
    }
}

So basically what im trying to do is:

Return a list of ShowData objects (big set) where any HashData (from small set) is found in ShowData BUT within the LINQ to Entity initial query to the DB.

I got close with:

private IEnumerable<ShowData> xyz(List<ShowData> aObj, List<ShowData> bObj)
    {
        IEnumerable<string> bStrs = bObj.Select(b => b.HashData).Distinct();
        return aObj.Join(bStrs, a => a.HashData, b => b, (a, b) => a);
    }
1
6
12/23/2011 9:15:43 AM

Popular Answer

Since you are using IEnumerable, you can use the Intersect Extension method instead of Join. If you want to return the big set you would want to intersect the result of the big set query with the smaller set. You would need to write an IEquality Comparer as shown here: http://msdn.microsoft.com/en-us/library/bb355408.aspx to compare your objects, then call the Intersect extension method:

return bStrs.Intersect(aObj, new MyEqualityComparer());
6
12/22/2011 7:56:25 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow