C#从另一个列表中减去一个列表或检查一个列表是否完全包含在另一个列表中 [英] C# subtracting one list from another or checking if one list is completly containt in another list
问题描述
如何从另一个列表中减去一个列表?
How to subtract one list from another?
List<string> l1 = new List<string> { "abc", "abc", "abc", "def" };
List<string> l2 = new List<string> { "abc" };
var r = l1.Except(l2).ToList();
这样做将导致r =>"def"而不是r =>"abc","abc","def".我的意思是,第二个列表一次只包含"abc".因此,我只想删除第一个列表的"abc"的一个实例.
Doing this results in r => "def" instead of r=> "abc", "abc", "def". I mean, the second list only contains "abc" one time. So I want to remove only one instance of "abc" of the first list.
顺便说一句:有没有一种方法可以检查一个列表是否完全包含在另一个列表中?表示当list1仅一次包含"abc"而list2两次包含"abc"时,list1中不包含list2.除
不适用于多个值.
Btw: Is there a way to check if one list is completely contained in another list?
Meaning when list1 only contains "abc" one time and list2 contains "abc" two times, list2 is not contained in list1. Except
doesn't work with multiple values.
推荐答案
您可以编写自己的扩展方法 MyExcept
You can write your own extension method MyExcept
public static IEnumerable<T> MyExcept<T>(this IEnumerable<T> orgList, IEnumerable<T> toRemove)
{
var list = orgList.ToList();
foreach(var x in toRemove)
{
list.Remove(x);
}
return list;
}
根据 Alexei Levenkov
的评论,有一点改进...
As per Alexei Levenkov
s comment, a little improvement...
public static IEnumerable<T> MyExcept2<T>(this IEnumerable<T> orgList, IEnumerable<T> toRemove)
{
var list = orgList.OrderBy(x => x).ToList();
foreach (var x in toRemove)
{
var inx = list.BinarySearch(x);
if (inx >= 0) list.RemoveAt(inx);
}
return list;
}
这篇关于C#从另一个列表中减去一个列表或检查一个列表是否完全包含在另一个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!