一道LINQ题,可以瞅一眼
public sealed class Product
{
public int Id { get; set; }
public string Category { get; set; }
public double Value { get; set; }
public override string ToString()
{
return string.Format("[{0}: {1} - {2}]", Id, Category, Value);
}
}
{
public int Id { get; set; }
public string Category { get; set; }
public double Value { get; set; }
public override string ToString()
{
return string.Format("[{0}: {1} - {2}]", Id, Category, Value);
}
}
数据源(可从数据库取出)
public static List<Product> GetList()
{
var products = new List<Product>
{
new Product {Id = 1, Category = "Electronics", Value = 15.0},
new Product {Id = 2, Category = "Groceries", Value = 40.0},
new Product {Id = 3, Category = "Garden", Value = 210.3},
new Product {Id = 4, Category = "Pets", Value = 2.1},
new Product {Id = 5, Category = "Electronics", Value = 19.95},
new Product {Id = 6, Category = "Pets", Value = 21.25},
new Product {Id = 7, Category = "Pets", Value = 5.50},
new Product {Id = 8, Category = "Garden", Value = 13.0},
new Product {Id = 9, Category = "Automotive", Value = 10.0},
new Product {Id = 10, Category = "Electronics", Value = 250.0},
};
return products; }
{
var products = new List<Product>
{
new Product {Id = 1, Category = "Electronics", Value = 15.0},
new Product {Id = 2, Category = "Groceries", Value = 40.0},
new Product {Id = 3, Category = "Garden", Value = 210.3},
new Product {Id = 4, Category = "Pets", Value = 2.1},
new Product {Id = 5, Category = "Electronics", Value = 19.95},
new Product {Id = 6, Category = "Pets", Value = 21.25},
new Product {Id = 7, Category = "Pets", Value = 5.50},
new Product {Id = 8, Category = "Garden", Value = 13.0},
new Product {Id = 9, Category = "Automotive", Value = 10.0},
new Product {Id = 10, Category = "Electronics", Value = 250.0},
};
return products; }
题目要求:
以 商品种类的第一个首字母按字母排序顺序进行分组,分组后的Product按按照价格进行排序。
请自己实现以上效果后,再看看下面的代码,有什么不同:
实现代码:
var lookup = products.ToLookup(item => Convert.ToChar(item.Category.Substring(0, 1))).OrderBy(item => item.Key);
foreach (IGrouping<char,Product> group in lookup)
{
Console.WriteLine(group.Key);
foreach (Product str in package.OrderBy(item => item.Value))
{
Console.WriteLine(" {0}",str);
}
}
你答对了吗?
请学会使用ToLookup
完!