什么是Linq查询,它将获得每个objX objX.created = {newest}?

时间:2010-02-19 16:49:10

标签: c# linq linq-to-sql

这对我来说是一个脑筋急转弯。我几乎不愿意寻求帮助,因为我担心我会错过无尽的,不眠之夜试图加密这个谜团。 JK

我有一个C#项目,我需要显示一个唯一对象列表,但只显示基于对象类型的最新对象。出于讨论目的,让我们谈谈“果实”。假设我有一个水果列表,每个水果都有一个“选择日期”。没有主键。所以,我的“Fruit”类型的通用列表可能看起来像......

{'Apple','1/2/2010'}
{'Apple','11/12/2009'}
{'Apple','2/14/2010'}
{'Grape','5/2/2009'}
{'Orange','10/30/2009'}
{'Mango','2/13/2010'}
{'Apple','6/30/2009'}
{'Orange','10/5/2009'}
{'Grape','2/1/2010'}

我需要能够将该清单减少到最新的每种水果类型。结果应该是......

{'Apple','2/14/2010'}
{'Orange','10/30/2009'}
{'Mango','2/13/2010'}
{'Grape','2/1/2010'}

在我的实际情况中,我正在使用Linq to SQL。所以,我想和我一直在做的事情保持一致。

这可能很简单,后来,我甚至会被问到尴尬。但是,我需要知道,所以我想我只需要做出牺牲。

6 个答案:

答案 0 :(得分:6)

这样的事情应该这样做:

var query = from item in db.Items
            group item by item.Fruit into grouped
            select grouped.OrderByDescending(x => x.Date)
                          .First();

换句话说,按水果名称分组,按日期按按每个组排序并获取第一个结果。

答案 1 :(得分:1)

您想对密钥执行分组(在本例中为Fruit),然后在值上排序组(在本例中为Created),从每个组中选择第一个项目,如下:< / p>

from each f in FruitCreatedDates
group f by f.Created into g
select new 
{ 
    Fruit = g.Key, 
    Newest = g.OrderedByDescending(fr => fr.Created).First() 
};

答案 2 :(得分:0)

我对Linq to SQL语法并不熟悉,但在SQL中你会使用一个不同的select,并在创建日期结合Order。

答案 3 :(得分:0)

看起来你需要一个groupby和一个max(日期)。我纯粹是以SQL的方式思考,但我相信你能够找到Linq。

答案 4 :(得分:0)

使用Min方法,提供如下的选择器lambda:

var list = new List<Fruit>() { 
    new Fruit() {Name = "Apple", Created = new DateTime(2010, 1, 2)},
    new Fruit() {Name = "Apple", Created = new DateTime(2010, 2, 2)},
    new Fruit() {Name = "Apple", Created = new DateTime(2010, 3, 2)},
    new Fruit() {Name = "Grape", Created = new DateTime(2011, 4, 2)},
    new Fruit() {Name = "Grape", Created = new DateTime(2011, 5, 2)},
    new Fruit() {Name = "Grape", Created = new DateTime(2011, 6, 2)},
};

var query =
        from fruit in list
        group fruit by fruit.Name into grouped
        select grouped.Min(f => f.Created);

答案 5 :(得分:0)

如果我是你,我会创建一个自定义对象来封装这些数据。通过这种方式,您可以根据自己的内容运行LINQ查询。

public struct Fruit
{
    public string Name;
    public string FreshDate;
}

然后我会像这样运行查询:

List<Fruit> fruitArray = new List<Fruit>
{
new Fruit { Name = "Apple", FreshDate = "1/2/2010"},
new Fruit { Name = "Apple", FreshDate = "11/12/2009"},
new Fruit { Name = "Apple", FreshDate = "2/14/2010"},
new Fruit { Name = "Grape", FreshDate = "5/2/2009"},
new Fruit { Name = "Orange", FreshDate = "10/30/2009"},
new Fruit { Name = "Mango", FreshDate = "2/13/2010"},
new Fruit { Name = "Apple", FreshDate = "6/30/2009"},
new Fruit { Name = "Orange", FreshDate = "10/5/2009"},
new Fruit { Name = "Grape", FreshDate = "2/1/2010"}
};

var resultArray = fruitArray.GroupBy(f => f.Name).Select(g => g.OrderBy(f => DateTime.Parse(f.FreshDate)).Last());

您不应该在多维字符串数组上运行查询。更容易阅读自定义对象。