Search code examples
c#.netlinqlistexcept

How to Attain a list of items of items not on another list


I want to attain a list of BeerNames from a list whose names are not on a second list.

var myList=(from f in Beers where ...
              select f.BeerNames).ToList

var storeList(from f in Store where...
                select f).ToList()

MyList will have some BeerNames that are not on StoreList. How do I find those BeerNames? I tried .Except and !Contains but I realize I'm doing something wrong, and missing some key bit of knowledge. thanks

If I change

var storeList(from f in Store where...
                select f).ToList()

to

var storeList(from f in Store where...
                select f.BeerNames).ToList()

then I can use except such as List1.Except(List2). I wasn't sure if there was a better way. Sorry folks if this isn't clear...I'm trying:)


Solution

  • var list1 = new String[] {"ABC1","ABC2", "ABC3", "ABC4"} ;
    var list2 = new String[] {"ABC3","ABC4", "ABC5", "ABC6"} ;
    var list3 = list1.Except(list2); // list3 holds ABC1, ABC2
    

    Except works fine.

    I suspect issue is in the item returned from the linq query. Seems like f.BeerNames in first, and f in StoreList are not pointing to same datatype.

    For heterogenous type

    var list1 = from s in new String[] {"ABC1","ABC2", "ABC3", "ABC4"} select new {BeerName=s,Id = Guid.NewGuid().ToString()}  ;
    var list2 = new String[] {"ABC3","ABC4", "ABC5", "ABC6"} ;
    var intermediateList = list1.Select(i=>i.BeerName).Except(list2);
    var list3 = from l1 in list1
            join l2 in intermediateList on l1.BeerName equals l2
            select l1;
    
    
    list1.Dump(); // run in linqPad
    intermediateList.Dump();// run in linqPad
    list3.Dump();// run in linqPad
    

    list3 returns following

    BeerName Id

    ABC1 569ace9a-66c4-46aa-bbf5-50d586a2886f

    ABC2 af456094-9692-4771-b489-8b3cca8aa938

    Use LinqPad to run the above, or remove .Dump() to execute in VS.