Linq RemoveAll删除所有项目

时间:2013-03-21 13:22:36

标签: c# linq

我有一个包含多条记录的数据行的newLinks。这是表结构

LinkSysId | LinkId | Col1 | Col2
1           1        str    str1
2           1        str5   str4 
3           2        str2   str3
4           2        str6   str7

我想创建一个linq查询,它会迭代集合并只留下前1个不同的LinkId记录:

LinkSysId | LinkId | Col1 | Col2
1           1        str    str 
3           2        str3   str3

我试着这样做

newLinks.RemoveAll(rowComp => newLinks.Any(rowDel => 
                   rowComp["linkId"].ToString() == rowDel["linkId"].ToString() 
                   &&  rowComp["linkSysId"].ToString() != rowDel["linkSysId"].ToString()));

但它会从集合中删除所有项目?谢谢你的帮助

3 个答案:

答案 0 :(得分:3)

有LINQ扩展库可以实现DistinctBy(),这正是您所需要的。但是,如果已添加相同的项目,则此小片段利用了hashset上的Add()方法返回false的事实:

var foundIds = new HashSet<int>();
var FirstLinkId = newLinks.Where(row=>foundIds.Add(row.LinkId)).ToList();

答案 1 :(得分:1)

&#34;创造新的&#34;的方法:

DataTable keepTheseRows = table.AsEnumerable()
    .GroupBy(r => r.Field<int>("LinkId"))
    .Select(g => g.First())  // takes the first of each group arbitrarily
    .CopyToDataTable();

答案 2 :(得分:1)

正如Tormod所说,最好的方法是使用DistinctBy()实现。

(特别是,看看Tormod的实现,你会发现它与下面的DistinctByImpl()方法有效,所以这个答案应该被视为他的扩展。)

如果使用DistinctBy(),解决方案就变得如此简单:

var uniques = list.DistinctBy(item => item.LinkId);

DistinctBy()可以找到using System; using System.Linq; using System.Collections.Generic; namespace Demo { public static class Program { public static void Main(string[] args) { List<Test> list = new List<Test> { new Test(1, 1), new Test(2, 1), new Test(3, 2), new Test(4, 2) }; var uniques = list.DistinctBy(item => item.LinkId); foreach (var item in uniques) { Console.WriteLine(item); } } } public class Test { public Test(int linkSysId, int linkId) { LinkSysId = linkSysId; LinkId = linkId; } public override string ToString() { return string.Format("LinkSysId = {0}, LinkId = {1}", LinkSysId, LinkId); } public int LinkSysId; public int LinkId; } static class EnumerableExt { public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return source.DistinctBy(keySelector, null); } public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { if (source == null) throw new ArgumentNullException("source"); if (keySelector == null) throw new ArgumentNullException("keySelector"); return DistinctByImpl(source, keySelector, comparer); } private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { var knownKeys = new HashSet<TKey>(comparer); return source.Where(element => knownKeys.Add(keySelector(element))); } } } 的良好实施,Jon Skeet's MoreLinq library也是available on NuGet

举个例子,这是一个使用MoreLinq的DistinctBy()实现副本的实现。不要使用此代码 - 使用NuGet下载原始注释代码。

{{1}}