4

请建议使用 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 of Sources 填充 Cs of Destinations(或其他类)?可以在这里使用 LINQ 吗?

提前致谢!

4

2 回答 2

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 })
);
于 2013-01-22T15:25:21.183 回答
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();

演示

于 2013-01-22T15:29:41.370 回答