ValueTuple.Create中的命名参数 [英] Named Parameters in ValueTuple.Create

查看:30
本文介绍了ValueTuple.Create中的命名参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中使用Value Tuple玩耍.

I was playing arround with the Value Tuple in C#.

首先提供一些演示数据:

First some demo data:

  #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

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

Then a method using the demo data:

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

到目前为止没有问题.

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

But if I want a result sorted by Product name I can do as following :

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中使用这些名称

And here I have my problem: when using ValueTuple.Create(...) can I name the parameters, so the names could be used in a OrderBy

我希望有这样的东西:

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

,然后在我的订单中使用该名称:

and then use the name in my orderBy:

OrderBy(e => e.ProductName)

推荐答案

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

You can directly create a named tuple within your Select and explictly indicate the names:

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

这篇关于ValueTuple.Create中的命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆