假设我有一个像这样的数据库记录列表:
Warehouse goods
A apple
A orange
B apple
B banana
是否可以使用linq选择两个对象,说对象A和对象B每个都包含其商品的集合?
答案 0 :(得分:0)
Linq更多的是查询,而不是你对查询结果的处理方式。这就是为什么您会看到Select
和Where
但不是Add
或Update
等方法的原因。
您可以获取查询的结果并将它们添加到两个单独的集合中,或者您可以迭代集合中的项目并对它们执行多个操作,例如检查它们并将它们添加到一个或多个集合中。 / p>
答案 1 :(得分:0)
你可以这样做:
using System;
using System.Collections.Generic;
using System.Linq;
namespace SO36322037
{
class Record
{
public string Warehouse { get; set; }
public string Goods { get; set; }
}
class Program
{
static void Main()
{
var list = new List<Record>
{
new Record {Warehouse = "A", Goods = "apple"},
new Record {Warehouse = "A", Goods = "orange"},
new Record {Warehouse = "B", Goods = "apple"},
new Record {Warehouse = "B", Goods = "banana"},
};
var result = list.GroupBy(l => l.Warehouse, l => l.Goods).ToList();
foreach (var warehouse in result)
{
Console.WriteLine($"Warehouse: {warehouse.Key}");
foreach (var goods in warehouse)
{
Console.WriteLine($"\tGoods: {goods}");
}
}
// This is your object A
var A = result.Single(x => x.Key == "A").ToList();
// This is your object B
var B = result.Single(x => x.Key == "B").ToList();
}
}
}
答案 2 :(得分:0)
如果我理解正确,你可以使用'group by'
做类似的事情var items = new List<Record>
{
new Record {Warehouse = "A", Goods = "apple"},
new Record {Warehouse = "A", Goods = "orange"},
new Record {Warehouse = "B", Goods = "apple"},
new Record {Warehouse = "B", Goods = "banana"},
};
var warehouses = from item in items
group item.Goods by item.Warehouse
你可以像这样迭代结果
foreach(var warehouse in warehouses){
//...
foreach(var item in warehouse){
//...
}
}