2

我有一些这样的结构列表:

struct va_data
{
  public int item_id;
  public int type_id;
  public double item_value;
  public DateTime value_date;
}

我尝试按 type_id 对列表进行分组,然后取 value_date 最大的项目,然后按 item_id 分组,只取 item_value 最小的项目

有我的语法

from x in dataList 
group x by x.type_id into grouped 
select grouped.Where(x => x.value_date == grouped.Max(y => y.value_date))
    .GroupBy(x => x.item_id) // and here i was stuck.


Example

var dataList = new []
{
   new va_data {item_id = 1, type_id = 1, item_value = 0, value_date = "2013.07.29"},
   new va_data {item_id = 1, type_id = 1, item_value = 1, value_date = "2013.07.30"},
   new va_data {item_id = 2, type_id = 1, item_value = 0, value_date = "2013.07.29"},
   new va_data {item_id = 2, type_id = 1, item_value = 1, value_date = "2013.07.29"},
   new va_data {item_id = 4, type_id = 2, item_value = 5, value_date = "2013.07.29"},
   new va_data {item_id = 4, type_id = 3, item_value = 9, value_date = "2013.07.30"},
};

The result must be 

var dataListResult = new []
{
   new va_data {item_id = 1, type_id = 1, item_value = 1, value_date = "2013.07.30"},
   new va_data {item_id = 2, type_id = 1, item_value = 0, value_date = "2013.07.29"},
   new va_data {item_id = 4, type_id = 2, item_value = 5, value_date = "2013.07.29"},
}
4

2 回答 2

1

给定以下课程

class va_data
{
  public int item_id;
  public int type_id;
  public double item_value;
  public DateTime value_date;
}

和您的示例数据,您可以使用这样的查询:

from data in dataList
group data by new {data.item_id, data.type_id} into g
let max_value_date = g.Max(x => x.value_date)
from i in g.Where(x => x.value_date == max_value_date)
group i by i.item_id into g2
let min_item_value = g2.Min(x => x.item_value)
from x in g2
where x.item_value == min_item_value
select x;

得到以下结果:

在此处输入图像描述

于 2013-07-29T10:34:37.570 回答
0

只需将您的查询分成两部分 - 获取每种类型的最新信息,然后获取每个项目的最少信息:

var latestOfEachType = 
             from d in dataList
             group d by d.type_id into typeGroup
             select typeGroup.OrderByDescending(x => x.value_date).First();

var result = from d in latestOfEachType
             group d by d.item_id into itemGroup
             select itemGroup.OrderBy(x => x.item_value).First();

此查询将作为单个查询执行。但在这种情况下,它看起来对我来说更具可读性。也不要使用可变结构!. 改用类。


编辑:因此你有几个最大日期的项目,然后查询需要两个小调整 - 选择日期为最大值的所有项目,并使用 SelectMany 迭代它们:

var latestOfEachType =
             from d in dataList
             group d by d.type_id into typeGroup
             let maxDate = typeGroup.Max(x => x.value_date)
             select typeGroup.Where(x => x.value_date == maxDate);

var result = from d in latestOfEachType.SelectMany(g => g)
             group d by d.item_id into itemGroup
             select itemGroup.OrderBy(x => x.item_value).First();
于 2013-07-29T10:43:00.397 回答