两个列表保存副本的区别 [英] Difference between two lists preserving duplicates
本文介绍了两个列表保存副本的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表:
VAR list1的=新的List<串GT; {A,A,B,C};
变种列表2 =新的List<串> {A,B};
和我想产生像
VAR的结果=新的[] {A,C};
凡列表所有从 list1的
元素从中删除列表2
我不认为有这种一个LINQ扩展方法,因为除了
删除重复
非LINQ的方式来做到这一点是:
VAR tempList = list1.ToList();
的foreach(在列表2 VAR项)
{
tempList.Remove(项目) ;
}
但我想知道如果有,我可能有一个LINQ扩展方法。错过
编辑:
由于有可能没有任何这里的扩展方法我做
公共静态类LinqExtensions
{
公共静态的IEnumerable< T> RemoveRange< T>(这个IEnumerable的< T> ;源,IEnumerable的< T>第二)
{
VAR tempList = source.ToList();
的foreach(第二VAR项)
{
tempList.Remove(项目);
}
返回tempList;
}
公共静态的IEnumerable< TFirst> RemoveMany< TFirst,TSecond>(这个IEnumerable的< TFirst>源,IEnumerable的< TSecond>第二个,Func键< TSecond,IEnumerable的< TFirst>>选择器)
{
VAR tempList = source.ToList();
的foreach
{
tempList.Remove(项目)(在second.SelectMany(选择)VAR项目);
}
返回tempList;
}
}
用法:
list1.RemoveRange(列表2)
解决方案
看着你的榜样,我想你的意思是一切从list2中的元素从list1的删除:
VAR lookup2 = list2.ToLookup(海峡=> STR);
VAR的结果=从list1的
组乙方对通过海峡进入strGroup
让missingCount
= Math.Max(0,strGroup.Count() - lookup2 [ strGroup.Key] .Count之间的())从missingStr
在strGroup.Take(missingCount)
选择missingStr;
I have two lists:
var list1 = new List<string> { "A", "A", "B", C" };
var list2 = new List<string> { "A", "B" };
and I would like to produce a list like
var result = new[] { "A", "C" };
Where the list is all the elements from list1
removed from list2
I don't think there is a Linq extension method for this since Except
removes duplicates.
The non-linq way to do this would be:
var tempList = list1.ToList();
foreach(var item in list2)
{
tempList.Remove(item);
}
but I am wondering if there is a Linq extension method that I might have missed.
Edit:
Since there probably aren't any here's an extension method I made.
public static class LinqExtensions
{
public static IEnumerable<T> RemoveRange<T>(this IEnumerable<T> source, IEnumerable<T> second)
{
var tempList = source.ToList();
foreach(var item in second)
{
tempList.Remove(item);
}
return tempList;
}
public static IEnumerable<TFirst> RemoveMany<TFirst, TSecond>(this IEnumerable<TFirst> source, IEnumerable<TSecond> second, Func<TSecond, IEnumerable<TFirst>> selector)
{
var tempList = source.ToList();
foreach(var item in second.SelectMany(selector))
{
tempList.Remove(item);
}
return tempList;
}
}
Usage:
list1.RemoveRange(list2)
解决方案
Looking at your example, I think you mean "all the elements from list2 removed from list1":
var lookup2 = list2.ToLookup(str => str);
var result = from str in list1
group str by str into strGroup
let missingCount
= Math.Max(0, strGroup.Count() - lookup2[strGroup.Key].Count())
from missingStr in strGroup.Take(missingCount)
select missingStr;
这篇关于两个列表保存副本的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文