ValueTuple.Create中的命名参数

编程入门 行业动态 更新时间:2024-10-25 20:31:37
本文介绍了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中的命名参数

本文发布于:2023-11-05 19:19:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   ValueTuple   Create

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!