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);
}
So far no problems.
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);
}
And here I have my problem: when using ValueTuple.Create(...) can I name the parameters, so the names could be used in a OrderBy
I was hoping for something like this:
select ValueTuple.Create(CategoryId : category.ID, ProductName : prod.Name)
and then use the name in my orderBy:
OrderBy(e => e.ProductName)
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);
Maybe it is better to provide same style to all linq query. I mean use "orderby" before select.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With