通过选择列表中的两个属性不同 [英] Select distinct by two properties in a list

查看:103
本文介绍了通过选择列表中的两个属性不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表<消息> 包含类型的属性的Guid 的DateTime (以及其他属性)。我想摆脱所有在列表中的项目,其中的Guid 的DateTime 是相同的(除外一)。会有时候,这两个属性是相同的列表中的其他项目,但其他属性也会有所不同,所以我不能只用 .Distinct()

 列表<消息>消息=的GetList();
//列表现在包含许多对象,它是由日期时间属性有序在messages.Distinct从对消息=(发生的事情吗?);

这就是我现在所拥有的,但似乎应该有一个更好的办法

 列表<消息>消息=的GetList();对(INT I = 0; I&下; messages.Count() -  1)//使用Messages.Count()-1,因为最后一个无关后要比较的
{
    如果(消息[I] .ID = =消息第[i + 1} .ID&放大器;&安培;信息[I] .date ==消息[I + 1] .date)
    {
        messages.RemoveAt第(i + 1);
    {
    其他
    {
         我++
    }
}


解决方案

LINQ到对象不以内置方式轻松提供这一功能,但的 MoreLINQ 有一个方便的 DistinctBy 方法:

 消息= messages.DistinctBy(M = gt;新建{m.id,m.date})了ToList()。

I have a list<message> that contains properties of type Guid and DateTime (as well as other properties). I would like to get rid of all of the items in that list where the Guid and DateTime are the same (except one). There will be times when those two properties will be the same as other items in the list, but the other properties will be different, so I can't just use .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? ); 

This is what I have right now, but it seems like there ought to be a better way

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++
    }
}

解决方案

LINQ to Objects doesn't provide this functionality easily in a built-in way, but MoreLINQ has a handy DistinctBy method:

messages = messages.DistinctBy(m => new { m.id, m.date }).ToList();

这篇关于通过选择列表中的两个属性不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆