我有一个类似的列表:
1
1
1
3
3
5
列表B如:
1
1
3
所需的结果就是减去这两个:
1
3
5
我该怎么做?
答案 0 :(得分:2)
如果您要删除的所有元素都被移除,那么您可以执行此操作。
df = structure(list(d = c("A", "B", "C", "D", "J", "M"), var1 = c("25",
"28", "55", "64", "cd", "dg"), var2 = c("26", "35", "46", "az",
"yz", "ck"), var3 = structure(c(2L, 3L, 1L, 5L, 1L, 4L), .Label = c("",
"abc", "abk", "ja", "lft"), class = "factor")), .Names = c("d",
"var1", "var2", "var3"), row.names = c(NA, -6L), class = "data.frame")
答案 1 :(得分:0)
这是一个扩展:
public static class EnumerableSetExtensions
{
public static IEnumerable<T> SetExcept<T>(this IEnumerable<T> source, IEnumerable<T> second, IEqualityComparer<T> comparer)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (second == null)
{
throw new ArgumentNullException(nameof(second));
}
if (comparer == null)
{
throw new ArgumentNullException(nameof(comparer));
}
var secondDict = second
.GroupBy(
keySelector: e => e,
comparer: comparer)
.ToDictionary(
keySelector: e => e.Key,
elementSelector: e => e.Count(),
comparer: comparer);
foreach (var item in source)
{
if (secondDict.ContainsKey(item))
{
var itemcount = secondDict[item] -= 1;
if (itemcount == 0)
{
secondDict.Remove(item);
}
}
else
yield return item;
}
}
public static IEnumerable<T> SetExcept<T>(this IEnumerable<T> source, IEnumerable<T> second)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (second == null)
{
throw new ArgumentNullException(nameof(second));
}
return SetExcept(source, second, EqualityComparer<T>.Default);
}
}
示例用法
public static void Main(string[] args)
{
var listA = new [] { 1, 1, 1, 3, 3, 5 };
var listB = new [] { 1, 1, 3 };
var listC = listA.SetExcept(listB).ToList();
Console.WriteLine("listA: {0}", string.Join(",", listA.Select(e => e.ToString())));
Console.WriteLine("listB: {0}", string.Join(",", listB.Select(e => e.ToString())));
Console.WriteLine("listC: {0}", string.Join(",", listC.Select(e => e.ToString())));
}
输出
listA: 1,1,1,3,3,5 listB: 1,1,3 listC: 1,3,5