![](/img/trans.png)
[英]What is the most efficient way to merge items with the same type in a generic list in C#?
[英]Using C#, what's an efficient way to compare/merge two generic lists of the same type?
如果我有两个通用列表List,并且我想基于Place.Id属性将所有唯一的Place对象合并到一个List中,那么有效地执行此操作的好方法是什么?
一个列表将始终包含50个,另一列表可能包含更多。
result = list1.Union(list2, new ElementComparer());
您需要创建ElementComparer来实现IEqualityComparer。 例如看这个
注意:.NET 3.5及更高版本。
如果您想强调效率,建议您编写一个小的方法自己进行合并:
List<Place> constantList;//always contains 50 elements. no duplicate elements
List<Place> targetList;
List<Place> result;
Dictionary<int, Place> dict;
for(var p in constantList)
dict.Put(p.Id,p);
result.AddRange(constantList);
for(var p in targetList)
{
if(!dict.Contains(p.Id))
result.Add(p)
}
如果要避免定义自己的ElementComparer并仅使用lambda表达式,可以尝试以下操作:
List<Place> listOne = /* whatever */;
List<Place> listTwo = /* whatever */;
List<Place> listMerge = listOne.Concat(
listTwo.Where(p1 =>
!listOne.Any(p2 => p1.Id == p2.Id)
)
).ToList();
本质上,这只会将Enumerable listOne与listTwo中所有元素的集合连接起来,这样元素就不在listOne和listTwo之间的交集中。
如果需要速度,则需要使用哈希机制进行比较。 我要做的是维护一个已经读取的ID的Hashset,然后如果尚未读取ID,则将元素添加到结果中。 您可以对任意数量的列表执行此操作,如果要在合并结束之前开始使用,可以返回IEnumerable而不是列表。
public IEnumerable<Place> Merge(params List<Place>[] lists)
{
HashSet<int> _ids = new HashSet<int>();
foreach(List<Place> list in lists)
{
foreach(Place place in list)
{
if (!_ids.Contains(place.Id))
{
_ids.Add(place.Id);
yield return place;
}
}
}
}
一个列表包含50个元素,而另一个列表包含更多元素,这一事实没有任何含义。 除非您知道列表是有序的...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.