【发布时间】: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 => 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 => (o.CategoryID, o.ProductName))之类的东西。最后的元组构造需要切换到对象 LINQ。 (请注意,您肯定希望在可能的情况下将orderby推送到查询中——对构建的元组进行排序可能会大大降低效率,具体取决于提供者。)