从列表中删除类似的项目

时间:2014-05-22 05:47:21

标签: c# linq entity-framework linq-to-entities

从SQL视图返回以下数据:

Name        CandidateID         Filled
Tom Jones   1003436             2014-05-09  07:13:53.087
Tom Jones   1003436             2014-05-09  07:13:18.957
Ed  Harris  1421522             2014-05-09  08:17:20.234

我只想要一个Tom Jones记录最新的填充时间。在从服务器获取数据时或从服务器获取数据后,如何在C#/ LINQ中实现此目的?

3 个答案:

答案 0 :(得分:5)

也许是这样的:

var q = from n in table
        group n by new {n.CandidateID,n.Name} into g
        select new 
        {
            CandidateID = g.Key.CandidateID, 
            Name = g.Key.Name, 
            Filled = g.Max(t=>t.Filled)
        };

测试类

class Foo
{
    public string Name { get; set; }
    public int CandidateID { get; set; }
    public DateTime Filled { get; set; }
}

测试用例

var ls=new List<Foo>
    {
        new Foo(){Name="Tom Jones",CandidateID=1003436,
                  Filled=DateTime.Parse("2014-05-09  07:13:53.087")},
        new Foo(){Name="Tom Jones",CandidateID=1003436,
                  Filled=DateTime.Parse("2014-05-09  07:13:18.957")},
        new Foo(){Name="Ed  Harris",CandidateID=1421522,
                  Filled=DateTime.Parse("2014-05-09  08:17:20.234")}
    };
    var q = 
        (from n in ls
        group n by new {n.CandidateID,n.Name} into g
        select new 
        {
            CandidateID = g.Key.CandidateID, 
            Name = g.Key.Name, 
            Filled = g.Max(t=>t.Filled)
        });

<强>输出

CandidateID     Name           Filled 
1003436         Tom Jones      09/05/2014 7:13:53 AM 
1421522         Ed  Harris     09/05/2014 8:17:20 AM 

答案 1 :(得分:2)

var q = from n in table
        group n by n.CandidateID into g
        select g.OrderByDescending(t=>t.Filled).FirstOrDefault();

答案 2 :(得分:0)

你需要Group by,如下所示

var distinctItems = ls.GroupBy(x => x.CandidateID).Select(y => y.First());