如何在执行 lgrouping 后从列表中检索 <Value>

How to Retrieve <Value> from a List after doing lgrouping

我可以知道如何在 Customer class 中显示 lgrouping 之后的字段吗?<Value> 参数在输出中吗?

List<Customer> customerList = new List<Customer>();                   

foreach (var customer in customerList.GroupBy(x => x.Age))
{
    Console.WriteLine("Age: " + customer.Key);

    //Display fields in customer.Value
}

class Customer
{
    public Guid CustomerId { get; set; }
    public int Age{ get; set; }
}

这里是你的代码的修改:

foreach (var customerMapElement in customers.GroupBy(x => x.Age))
        {
            Console.WriteLine("Age: " + customerMapElement.Key);
            foreach (var customer in customerMapElement)
                 Console.WriteLine("Customer: " + customer.CustomerId);

            //Display fields in customer.Value
        }

你必须在你的 foreach sinc 客户中添加一个 foreach 在你的代码中是一个列表,而在 lin

var customer in customerList.GroupBy(x => x.Age)

上面代码中的customer变成了一个list,所以要用foreach来使用里面的数据
您可以使用下面的代码

           List<Customer> customerList = new List<Customer>() {
                new Customer() {CustomerId=1,Age=10}, 
                new Customer() {CustomerId=2,Age=20},
                new Customer() {CustomerId=3,Age=20},
                new Customer() {CustomerId=4,Age=30},
                new Customer() {CustomerId=5,Age=10},
                };
            foreach (var customer in customerList.GroupBy(x => x.Age))
            {
                foreach (var item in customer)
                {
                    Console.WriteLine("Age: " + item.Age+" and "+item.CustomerId+"\n");
                }
                
            }