如何获取不在另一个列表中的项目列表

本文关键字:列表 另一个 项目 何获取 获取 | 更新日期: 2023-09-27 18:33:27

我想从名称不在第二个列表中的列表中获取BeerNames列表。

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

MyList将有一些不在StoreList上的啤酒名称。我如何找到这些啤酒名称?我尝试了.Except!Contains,但我意识到我做错了什么,并且缺少一些关键的知识。谢谢

如果我改变

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

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

那么我可以使用,除了List1.Except(List2).我不确定是否有更好的方法。对不起,伙计们,如果这不清楚...我正在尝试:)

如何获取不在另一个列表中的项目列表

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

除了工作正常。

我怀疑问题出在从 linq 查询返回的项目上。似乎第一个中的 f.BeerNames 和 StoreList 中的 f 不指向相同的数据类型。

对于异构型

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 返回以下内容

啤酒名称编号

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

ABC2 af456094-9692-4771-b489-8b3cca8aa938

使用 LinqPad 运行上述操作,或删除 .要在 VS 中执行的 dump()。

除非应该使用字符串类型

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