我有两个列表对象,如
list1 =[{"id":"101","name":"one"},{"id":"102","name":"two"},{"id":"103","name":"three"}]
list2 =[{"id":"111","name":"one"},{"id":"112","name":"two"},{"id":"114","name":"four"},{"id":"115","name":"five"}]
在上面两个列表中包含重复的名称值。现在我想根据name属性获取唯一的名称对象。 输出: -
result =[{"id":"103","name":"three"},{"id":"114","name":"four"},{"id":"115","name":"five"}]
答案 0 :(得分:1)
您可以使用Linq
扩展功能并执行此操作。
var result = list1.Concat(list2)
.GroupBy(x=>x.name)
.Where(x=>x.Count() == 1)
.Select(x=>x.FirstOrDefault())
.ToList();
答案 1 :(得分:0)
var common = list1.Select(a => a.name).Intersect(list2.Select(b => b.name));
答案 2 :(得分:0)
假设您在JSON反序列化过程之后有模型列表:
var list1 = new List<Model>();
var list2 = new List<Model>();
由于您需要删除每个列表中相交的所有元素并返回唯一元素,因此请使用Except或RemoveAll:
var target = list1.Except(list2);
// or use:
var target = list1.RemoveAll(item => list2.Contains(item));
使用HashSet的另一种方法:
var hashSet = new HashSet<Model>(list2);
list1.RemoveAll(item => hashSet.Contains(item));
参考:Remove elements from one List<T> that are found in another