为具有匿名类型的 linq 查询返回指定类型

returning specified type for a linq query with anonymous type

我有这个查询:

DbQuery<Logs> logs = context.GetQuery<Logs>();
var MessageLogs =
    logs.Where(
        s =>
            s.DATE == date.Date
        .GroupBy(s => new {s.DATE, s.ID})
        .Select(
            g => new {Date = g.Key.DATE, SID = g.Key.ID, Count = g.Count()})
        .GroupBy(x => x.SID, x => new {x.Date, x.Count});

我有这两个 classess:

public class Data
{
    public Values[] Val { get; set; }
    public string Key { get; set; }
}

还有这个:

public class Values
{
    public string type1 { get; set; }
    public string type2 { get; set; }
}

我想做的就是将该查询用于 return 类型的数据。 class 中的键数据是 SID,值列表应该是计数和日期作为 type1 和 type2。 我知道我可以用匿名类型做到这一点,但我不知道怎么做,我尝试了很多方法,但都错了。

 EDIT:

我有这个问题

    logs.Where(
        s =>
            s.DATE == date.Date
        .GroupBy(s => new {s.DATE, s.ID})
        .Select(
            g => new {Date = g.Key.DATE, SID = g.Key.ID, Count = g.Count()})

这个查询 return 是这样的:

 key   date      count
----------------------------
1021   2012        1
1021   2013       5
1022   2001        10
1023   2002        14

我想要的是基于每个 id 的值列表 事实上 return 类型应该是数据的类型,例如这个 id 是关键

key=1021 and Values[] should be type1=2012, type2=1 and type1=2013, type2=5

鉴于您当前查询的 returns 个元素 key/date/count,听起来您可能只想:

var result = query.GroupBy(
    x => x.Key,
    (key, rows) => new Data {
       Key = key,
       Val = rows.Select(r => new Values { type1 = r.Date, type2 = r.Count })
                 .ToArray();
    });

基本上this overload需要:

  • 来源
  • 一键选择器
  • 从键和匹配行到结果元素的转换(在您的例子中是 Data 的实例)