Search code examples
c#linqtuplesintersectionilist

List intersection by criteria in .NET


Here is my point: here is data class:

class Data
{
public string name; 
public int version;
}

here is data lists:

Ilist<Data> List_old = {new Data{name = "1", version = 1}, new Data{name = "2", version = 1}};
Ilist<Data> List_new = {new Data{name = "1", version = 2}, new Data{name = "3", version = 1}, new Data{name = "2", version = 1}};

As result I need a list of tuples - IList<Tuple<Data, Data>> - first data object is from List_new, second from List_old, taken by criteria - data objects have the same name but - first have greater version that the second OR second is null if there in List_old there is no any data item with the same name from List_new. Considering that the result should be:

IList<Tuple<Data, Data>> result = { {List_new[0], List_old[0]}, {List_new[1], null}};

could You help with the LINQ code which could perform that? I blow my brains with this...


Solution

  • If I've interpreted your question correctly:

    var q = 
        (from n in List_new
        join tmp in List_old on n.name equals tmp.name into g
        from o in g.DefaultIfEmpty()
        where o == null || o.version < n.version
        select new Tuple<Data, Data>(n, o)).ToList();