【问题标题】:IGrouping <decimal,string> does not contain a defintion for 'name'IGrouping <decimal,string> 不包含“名称”的定义
【发布时间】:2017-07-14 22:09:52
【问题描述】:

使用 LINQ 和 lambda 表达式,我正在尝试将已提取的数据写入文本文件。

using (var contextDb = new TimoToolEntities())
{
    using (var writeFile = new StreamWriter(saveTo))
    {

        var randomData = contextDb.WorkCenter_Operations.Where(d =>  d.Job_Number >= 1 && d.Part_Number.Length >= 1 && d.Oper_Number >= 1 )
        .OrderBy(d => d.Oper_Number)
        .GroupBy(d =>  d.Job_Number , d => d.Part_Number ).ToList();

        foreach (var record in randomData)
        {
            Console.WriteLine(record.Job_Number + "," + record.Part_Number); // error here
        }
    }
    Console.ReadLine();
}

我收到错误“IGrouping 不包含“名称”的定义,并且找不到接受“IGrouping”类型的第一个参数的扩展方法“名称”。

我环顾四周并相信这些对象是匿名的,但我无法找到可行的修复方法。

【问题讨论】:

  • 如果将record.Job_Number 替换为record.Key 会发生什么?
  • 这会起作用,但似乎没有办法指定作业编号或零件编号。它只是给出存储在record.key中的任何值
  • record.Key 中存储了什么?
  • Well IGrouping 大致是一个带有 Key 属性的集合,并且有据可查。真正的问题是什么?
  • 尝试:Console.WriteLine(string.Format("Job_Number: {0} Part_Numbers: {1}", record.Key, string.Join(",", record)));跨度>

标签: c# entity-framework linq


【解决方案1】:

当你使用GroupBy这个重载时

.GroupBy(d =>  d.Job_Number , d => d.Part_Number )

第一个 lambda 是一个键选择器(您按 Job_Number 分组),第二个是一个值选择器。您的record 将是Part_Number 的集合,其中Job_Number 作为键。

这个 MSDN 示例说明了基本用法:

// Group the pets using Age as the key value 
// and selecting only the pet's Name for each value.
IEnumerable<IGrouping<int, string>> query =
    pets.GroupBy(pet => pet.Age, pet => pet.Name);

// Iterate over each IGrouping in the collection.
foreach (IGrouping<int, string> petGroup in query)
{
    // Print the key value of the IGrouping.
    Console.WriteLine(petGroup.Key);
    // Iterate over each value in the 
    // IGrouping and print the value.
    foreach (string name in petGroup)
        Console.WriteLine("  {0}", name);
}

您的意图不是 100% 明确的,所以如果您真的想按多个字段进行分组,请使用不同的重载,如下所示:

.GroupBy(d => new { d.Job_Number, d.Part_Number })

那么您的record 将是您的任何数据的集合,并将有一个匿名密钥供您访问,例如record.Key.Job_Number

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多