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

杀马特。学长 韩版系。学妹 提交于 2019-12-11 15:38:13

问题


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:)


回答1:


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.




回答2:


Except should work with the string type

var myList = MyFrig.Select(f => f.BeerNames).Except(Store).ToList();


来源:https://stackoverflow.com/questions/10500850/how-to-attain-a-list-of-items-of-items-not-on-another-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!