Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...