【问题标题】:Named Parameters in ValueTuple.Create (2)ValueTuple.Create 中的命名参数 (2)
【发布时间】:2019-03-15 10:01:25
【问题描述】:

在另一个SO Question 中,我询问了ValueTuple.Create 中的命名参数。但是由于我的示例代码对我的问题不正确,所以我没有得到我想要的答案。所以我们又来了:

第一个演示数据:

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 IQueryable<Category> Categories { get; } = new List<Category>()
        {
            new Category(){Name="Beverages", ID=001},
            new Category(){ Name="Condiments", ID=002},
        }.AsQueryable();

        public IQueryable<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},
        }.AsQueryable();

    }

注意 IQueryable

然后是我的问题:

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

但如果我想要按产品名称排序的结果,我必须使用OrderBy(e =&gt; e.Item2)。我可以以某种方式摆脱我的 Order by 中的 Item1 和 Item2 名称吗

由于我有一个 IQueryable 接口,我必须使用 ValueTuple.Create

【问题讨论】:

  • LINQ 还不支持元组,抱歉。您将不得不接受from ... orderby prod.Name select new { CategoryID = category.ID, ProductName = prod.Name }).AsEnumerable().Select(o =&gt; (o.CategoryID, o.ProductName)) 之类的东西。最后的元组构造需要切换到对象 LINQ。 (请注意,您肯定希望在可能的情况下将orderby 推送到查询中——对构建的元组进行排序可能会大大降低效率,具体取决于提供者。)

标签: c# .net c#-7.0


【解决方案1】:

我找到了一个解决方法:我可以做一个类型案例:

    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 ((int CategoryId, string ProductName))ValueTuple.Create(category.ID, prod.Name)).OrderBy(e => e.ProductName);
    }

【讨论】:

  • 请注意,虽然这会解析,但并非所有 LINQ 提供程序都支持ValueTuple.Create。 (事实上​​,几乎没有,除了 LINQ to Objects。)对于那些这样做的人,演员表将是透明的,所以那一点没关系。
猜你喜欢
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
  • 2018-06-11
  • 2012-10-09
相关资源
最近更新 更多