简体   繁体   中英

IGrouping <decimal,string> does not contain a defintion for 'name'

Using LINQ and lambda expressions, I am trying to write data that I have pulled to a text file.

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();
}

I am getting the error the 'IGrouping does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type 'IGrouping' could be found.

I have looked around and believe that the objects are anonymous, but I haven't been able to find a fix that will work.

When you use this overload of GroupBy

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

the first lambda is a key selector (you group by Job_Number ) and the second one is a value selector. Your record will be a collection of Part_Number with Job_Number as a key.

This MSDN example illustrates the basic usage:

// 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);
}

Your intent is not 100% clear, so just in case you actually wanted to group by multiple fields, use a different overload like this:

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

Then your record will be a collection of whatever your data is and will have an anonymous key where you can access for example record.Key.Job_Number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM