【问题标题】:How to Attain a list of items of items not on another list如何获得不在另一个列表中的项目列表
【发布时间】:2012-05-17 01:39:03
【问题描述】:

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

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

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

MyList 将包含一些不在 StoreList 中的 BeerName。我如何找到那些 BeerNames?我尝试了.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)之外。我不确定是否有更好的方法。对不起,如果这不清楚...我正在尝试:)

【问题讨论】:

标签: c# .net linq list except


【解决方案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

除了工作正常。

我怀疑问题出在 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运行上面的,或者去掉.Dump()在VS中执行。

【讨论】:

  • Tilak,我认为我无法将 list1 与 List2 进行比较,因为 list2 是一个商店列表。我试过 List2.Select(x=>x.BeerName).Except(List1),但这会从 List2 返回数据。
  • list1,list2, list3 只是示例。您有 2 个案例 1. 您只需要选定的字段(比如说 BeerName)。两个查询中选择的字段相同(即 x.BeerName 是字符串,List1 是字符串列表),那么 List2.Select(x=>x.BeerName).Except(List1) 应该可以工作 2. 如果查询结果是异类的,并且您需要 list2 项的所有字段,条件是 BeerName 不应存在于列表 1 中,需要连接。
【解决方案2】:

除了应该使用字符串类型

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

【讨论】:

  • 嗨,阿杜奇。 myList 已经有一个有效的啤酒列表。我想要的是第三个查询,它将 myList 与 storeList 进行比较,结果是 myList 中不在 storeList 中的啤酒列表。 MyFrig 是一个不好的例子,抱歉。我会改的。
猜你喜欢
  • 2020-06-20
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多