通过列表中的两个属性选择distinct
我有一个list
,其中包含Guid
和DateTime
类型的属性(以及其他属性)。 我想摆脱该列表中Guid
和DateTime
相同的所有项目(除了一个)。 有时这两个属性将与列表中的其他项相同,但其他属性将不同,所以我不能只使用.Distinct()
List messages = GetList(); //The list now contains many objects, it is ordered by the DateTime property messages = from p in messages.Distinct( what goes here? );
这就是我现在所拥有的,但似乎应该有更好的方法
List messages = GetList(); for(int i = 0; i < messages.Count() - 1) //use Messages.Count() -1 because the last one has nothing after it to compare to { if(messages[i].id == messages[i+1}.id && messages[i].date == message[i+1].date) { messages.RemoveAt(i+1); { else { i++ } }
LINQ to Objects不能以内置方式轻松提供此function,但MoreLINQ有一个方便的DistinctBy
方法:
messages = messages.DistinctBy(m => new { m.id, m.date }).ToList();
Jon Skeet的DistinctBy
肯定是要走的路,但是如果你有兴趣定义自己的扩展方法,你可能会想到这个更简洁的版本:
public static IEnumerable DistinctBy (this IEnumerable source, Func keySelector) { var known = new HashSet(); return source.Where(element => known.Add(keySelector(element))); }
它具有相同的签名:
messages = messages.DistinctBy(x => new { x.id, x.date }).ToList();
那这个呢?
var messages = messages .GroupBy(m => m.id) .GroupBy(m => m.date) .Select(m => m.First());
您可以查看我的PowerfulExtensions库。 目前它处于一个非常年轻的阶段,但你已经可以使用Distinct,Union,Intersect等方法,除了任何数量的属性;
这是你如何使用它:
using PowerfulExtensions.Linq; ... var distinct = myArray.Distinct(x => xA, x => xB);
试试这个,
var messages = (from g1 in messages.GroupBy(s => s.id) from g2 in g1.GroupBy(s => s.date) select g2.First()).ToList();