请告知哪些是用C#中的另一个类的列表属性填充列表中的类属性的最佳方法。
我有
class Source
{
public object A {get; set;}
public object B {get; set;}
public object C {get; set;}
}
class Destination
{
public object A {get; set;}
public object B {get; set;} // (A,B) is a unique key
public List<object> Cs {get; set;}
public object D {get; set;}
}
然后我
List <Destination> destinations; // Cs = null
List <Source> sources; //may have zero, one or more than one Cs for (A,B)
如何使用C源填充目标(或其他类)的C?可以在这里使用LINQ吗?
提前致谢!
答案 0 :(得分:3)
LINQ救援:
sources = destinations.SelectMany(d => d.Cs);
你可能想要
sources = destinations.SelectMany(d =>
d.Cs.Select(c => new Source { A = d.A, B = d.B, C = c })
);
答案 1 :(得分:3)
按A和B(您的唯一键)对来源进行分组,然后从组中的所有项目中选择C:
var destinations = from s in sources
group s by new { s.A, s.B } into g
select new Destination()
{
A = g.Key.A,
B = g.Key.B,
Cs = g.Select(x => x.C).ToList()
};
如果您需要更新现有目的地,请更新
foreach(var d in destinations)
d.Cs = sources.Where(s => s.A == d.A && s.B && d.B).ToList();
或(我相信这会更快)
var lookup = sources.ToLookup(s => new { s.A, s.B }, s => s.C);
foreach (var d in destinations)
d.Cs = lookup[new { d.A, d.B }].ToList();