使用LINQ删除重复的记录 [英] Remove duplicate records using LINQ

查看:55
本文介绍了使用LINQ删除重复的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用linq来删除重复的记录.我希望最终列表将包含具有最新日期的唯一记录.我有以下列表

I want to use linq to object to remove duplicate records. I want that final list will contain unique records with the latest Date. I have the following list

AId             BId           C(date)
**1              2               24/5/2015**
3                6               24/5/2015
**1              2               23/5/2015** (Need To Remove)

我要删除记录3.

有什么建议吗?

推荐答案

您可以使用 GroupBy ,然后将 Select OrderByDescending 一起订购日期.

You can use GroupBy and then Select with OrderByDescending to order the dates.

public class Item 
{
    public int Aid {get;set;}

    public int Bid {get;set;}

    public DateTime CDate {get;set;}
}

void Main()
{
    var items = new List<Item>
    {
        new Item { Aid = 1, Bid = 2, CDate = new DateTime(2015, 5, 24)},
        new Item { Aid = 3, Bid = 6, CDate = new DateTime(2015, 5, 24)},
        new Item { Aid = 1, Bid = 2, CDate = new DateTime(2015, 5, 23)},        
    };

    var result =  items.GroupBy(i => i.Aid)
                  .Select(group => 
                        new { Key = group.Key,
                              Items = group.OrderByDescending(x => x.CDate) })
                  .Select (g => g.Items.First());


    result.Dump();
}

这篇关于使用LINQ删除重复的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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