我正在研究 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)