34

我有一个list<message>包含类型GuidDateTime(以及其他属性)的属性。我想删除该列表中与GuidDateTime相同的所有项目(除了一个)。有时这两个属性会与列表中的其他项目相同,但其他属性会有所不同,所以我不能只使用.Distinct()

List<Message> 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<Message> 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++
    }
}
4

5 回答 5

88

LINQ to Objects 无法以内置方式轻松提供此功能,但MoreLINQ有一个方便的DistinctBy方法:

messages = messages.DistinctBy(m => new { m.id, m.date }).ToList();
于 2012-08-04T18:40:02.513 回答
18

Jon Skeet'sDistinctBy绝对是要走的路,但是如果你有兴趣定义自己的扩展方法,你可能会喜欢这个更简洁的版本:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    var known = new HashSet<TKey>();
    return source.Where(element => known.Add(keySelector(element)));
}

具有相同的签名:

messages = messages.DistinctBy(x => new { x.id, x.date }).ToList();
于 2012-08-04T20:24:44.930 回答
2

尝试这个,

 var messages = (from g1 in messages.GroupBy(s => s.id) from g2 in g1.GroupBy(s => s.date) select g2.First()).ToList();
于 2018-08-10T19:42:20.290 回答
1

您可以查看我的PowerfulExtensions库。目前它还处于非常年轻的阶段,但您已经可以在任意数量的属性上使用 Distinct、Union、Intersect、Except 等方法;

这是你如何使用它:

using PowerfulExtensions.Linq;
...
var distinct = myArray.Distinct(x => x.A, x => x.B);
于 2013-08-15T20:23:36.300 回答
0

那这个呢?

var messages = messages
               .GroupBy(m => m.id)
               .GroupBy(m => m.date)
               .Select(m => m.First());
于 2012-08-04T18:48:36.663 回答