所以这是一个困扰我好几个小时的设计问题,我必须联系小组寻求帮助。我有一个包含数千个共享实体的集合,需要从两个列表中包含的三个不同属性中检索不同的管理器列表,两个管理器位于Stores列表中,一个管理器来自仓库集合。
为了简化问题,我编写了一个简单的控制台程序,突出了挑战。我把它扔在一起,所以是的,我知道这是低效的,但它证明了问题:
public class Program
{
static void Main(string[] args)
{
DistributionGroup d = new DistributionGroup();
Console.WriteLine("====Store Managers====");
foreach(Manager m in d.Stores.Select(m => m.StoreManager).Distinct())
{
Console.WriteLine("{0}:{1}", m.Id, m.Name);
}
Console.WriteLine("=====Inv. Managers=====");
foreach (Manager m in d.Stores.Select(m => m.InventoryManager).Distinct())
{
Console.WriteLine("{0}:{1}", m.Id, m.Name);
}
Console.WriteLine("===Warehouse Managers===");
foreach (Manager m in d.Warehouses.Select(m => m.WarehouseManager).Distinct())
{
Console.WriteLine("{0}:{1}", m.Id, m.Name);
}
}
}
public class DistributionGroup
{
private Manager m1 = new Manager(1, "Bob Wilson");
private Manager m2 = new Manager(2, "Chris Warren");
private Manager m3 = new Manager(3, "Mike Olsen");
private Manager m4 = new Manager(4, "Aaron Erikson");
public List<RetailStore> Stores;
public List<Warehouse> Warehouses;
public DistributionGroup()
{
RetailStore s1 = new RetailStore(1, m1, m1);
RetailStore s2 = new RetailStore(2, m1, m3);
RetailStore s3 = new RetailStore(3, m2, m2);
Warehouse w1 = new Warehouse(1, m4);
Warehouse w2 = new Warehouse(2, m2);
Stores = new List<RetailStore>();
Stores.Add(s1);
Stores.Add(s2);
Stores.Add(s3);
Warehouses = new List<Warehouse>();
Warehouses.Add(w1);
Warehouses.Add(w2);
}
}
public class Manager
{
public int Id;
public string Name;
public Manager(int id, string name)
{
Id = id; Name = name;
}
}
public class RetailStore
{
public int Id;
public Manager StoreManager;
public Manager InventoryManager;
public RetailStore(int id, Manager mgr, Manager inventoryMgr)
{
Id = id;
StoreManager = mgr;
InventoryManager = inventoryMgr;
}
}
public class Warehouse
{
public int Id;
public Manager WarehouseManager;
public Warehouse(int id, Manager mgr)
{
Id = id;
WarehouseManager = mgr;
}
}
我需要做的是从所有三个属性生成一个独特的Managers列表:
因此,按照示例,控制台输出将只是:
1:Bob Wilson 2:Chris Warren
3:Mike Olsen
4:Aaron Erikson
我一直在努力弄清楚语法,但LINQ不是一种力量,我希望这个小组可以帮助我。
答案 0 :(得分:5)
好像你需要使用Enumerable.Union
var allManagers = d.Stores.Select(m => m.StoreManager).Union(d.Stores.Select(m => m.InventoryManager))
.Union(d.Warehouses.Select(m => m.WarehouseManager));
foreach (Manager m in allManagers)
{
Console.WriteLine("{0}:{1}", m.Id, m.Name);
}
请注意,Union
会返回输入序列中的唯一值,因此无需调用Distinct
。