【问题标题】:Named Parameters in ValueTuple.CreateValueTuple.Create 中的命名参数
【发布时间】:2019-03-15 08:52:50
【问题描述】:

我正在玩 C# 中的 Value Tuple。

首先是一些演示数据:

  #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)

【问题讨论】:

    标签: c# .net c#-7.0


    【解决方案1】:

    您可以直接在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);
    

    【讨论】:

    • 谢谢,我使用 ValueTuple.Create 修复了
    【解决方案2】:

    也许最好为所有 linq 查询提供相同的样式。我的意思是在选择之前使用“orderby”。

    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
                    orderby prod.Name
                    select ValueTuple.Create(category.ID, prod.Name);
            }
    

    【讨论】:

    • order by 的唯一 putpost 是为了说明我的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-06-11
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多