本文介绍了Linq-将匿名类型转换为具体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下linq语句:

I'm working with the following linq statement:

        var suppliers = SupplierView.Select()
            .GroupBy(x => x.Name.Substring(0, 1).ToUpper(),
                (alphanumeric, suppliers) => new
                {
                    Alphanumeric = alphanumeric,
                    Suppliers = suppliers.OrderBy(x => x.Name).ToList()
                })
            .OrderBy(x => x.Alphanumeric);

我想从方法中返回此值,但是我相信我将需要使用具体类型而不是匿名类型.

I'd like to return this from a method, however to do so I beleiev i'll need to use a concrete type rather an anonymous type.

这是具体类型:

public class AlphanumericSuppliers
{
    public string Alphanumeric { get; set; }
    public IOrderedEnumerable<Supplier> Suppliers { get; set; }
}

但是,我很难获得将匿名类型转换为具体类型的正确语法.

However, I'm having difficulty getting the correct syntax to convert the anonymous type to my concrete type.

有人建议吗?

推荐答案

仅创建具体类型的实例(不需要在LINQ中使用匿名类型):

Simply create instances of the concrete type (there is no requirement to use an anonymous types in LINQ):

var suppliers = SupplierView.Select()
        .GroupBy(x => x.Name.Substring(0, 1).ToUpper(),
            (alphanumeric, suppliers) => new AlphanumericSuppliers // concrete
            {
                Alphanumeric = alphanumeric,
                Suppliers = suppliers.OrderBy(x => x.Name).ToList() // *
            })
        .OrderBy(x => x.Alphanumeric);

这篇关于Linq-将匿名类型转换为具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:28