繁体   English   中英

如何将列表匿名类型与另一个列表进行比较

[英]How to compare list anonymous type to another list

我正在尝试使用Except来比较两个列表,但一个是匿名类型。

例如:

 var list1 = customer.Select(x => new { x.ID, x.Name }).ToList();
 var list2 = existcustomer.Select(x => x.ID).ToList();

我试图比较两个列表 ID 并返回一个列表名称列表。

我的代码:

var checkIfCustomerIdNotExist = list1.Where(x => x.ID.ToList().Except(list2)).Select(x =>  x.Name).ToList();

我想知道是否有任何解决方法。

我建议使用字典而不是列表

//create a dictionary of ID to name
var customerDict = customer.ToDictionary(x => x.ID, x => x.Name); 
//get your list to compare to
var list2 = existcustomer.Select(x => x.ID).ToList(); 
//get all entries where the id is not in the second list, and then grab the names
var newNames = customerDict.Where(x => !list2.Contains(x.Key)).Select(x => x.Value).ToList(); 

一般来说,最好考虑一下哪种数据结构最适合您的数据。 在您的情况下, list1 包含一个元组列表,其中需要使用 ID 来查找 Name - 使用更适合它的数据结构(字典)可以更轻松,更清晰地解决您的问题

请注意,该解决方案假定 ID 是唯一的,如果存在具有不同名称的重复 ID,您可能需要 Dictionary<string, List< string >> 而不仅仅是 Dictionary<string,string> - 但这可能需要的不仅仅是一个单行 linq,虽然代码会非常相似

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM