ValueTuple.Create 中的命名参数

2024-03-18

我正在研究 C# 中的值元组。

首先是一些演示数据:

  #region Data
    public class Product
    {
        public string Name { get; set; }
        public int CategoryID { get; set; }
    }

    public class Category
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }

    public class Data
    {
        public List<Category> Categories { get; } = new List<Category>()
        {
            new Category(){Name="Beverages", ID=001},
            new Category(){ Name="Condiments", ID=002},
        };

        public List<Product> Products { get; } = new List<Product>()
        {
            new Product{Name="Cola",  CategoryID=001},
            new Product{Name="Tea",  CategoryID=001},
            new Product{Name="Mustard", CategoryID=002},
            new Product{Name="Pickles", CategoryID=002},
        };

    }
    #endregion

然后是使用演示数据的方法:

public static IEnumerable<(int CategoryId, string ProductName)> GetList()
{
    var data = new Data();
    return
        from category in data.Categories
            join prod in data.Products on category.ID equals prod.CategoryID
            select ValueTuple.Create(category.ID, prod.Name);
}

到目前为止没有问题。

但如果我想要按产品名称排序的结果,我可以执行以下操作:

public static IEnumerable<(int CategoryId, string ProductName)> GetList()
        {
            var data = new Data();
            return
                (from category in data.Categories
                    join prod in data.Products on category.ID equals prod.CategoryID
                    select ValueTuple.Create(category.ID, prod.Name)).OrderBy(e => e.Item2);
        }

这里我有我的问题:当使用 ValueTuple.Create(...) 时,我可以命名参数,以便可以在 OrderBy 中使用这些名称

我希望有这样的事情:

select ValueTuple.Create(CategoryId : category.ID, ProductName : prod.Name)

然后在我的 orderBy 中使用该名称:

OrderBy(e => e.ProductName)

您可以直接在您的内部创建一个命名元组Select并明确指出名称:

(
    from category in data.Categories
    join prod in data.Products on category.ID equals prod.CategoryID
    select (CategoryId: category.Id, ProductName: prod.Name)
).OrderBy(e => e.ProductName);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ValueTuple.Create 中的命名参数 的相关文章

随机推荐