LINQ - c#flatten collection to dictionary

时间:2015-03-04 23:56:45

标签: c# linq

我有以下数据结构:

class customer
{
      List<string> photoIds;
      string fullname;
}

样品采集:

新客户(){new [] {&#34; 1&#34;,&#34; 2&#34;,&#34; 3&#34;},&#34;客户1&#34;} ;

新客户(){new [] {&#34; 5&#34;,&#34; 8&#34;,&#34; 10&#34;},&#34;客户2&#34;} ;

新客户(){new [] {&#34; 3&#34;,&#34; 11&#34;,&#34; 4&#34;},&#34;客户3&#34;} ;

我想要实现的是将以下数据转换为Dictionary,其中key是photoid,值是fullname

{1, Cust 1}
{2, Cust 1}
{3, Cust 1}
{5, Cust 2}
{8, Cust 2}
{10, Cust 2}
{3, Cust 3}
{11, Cust 3}
{4, Cust 3}

有什么帮助?

1 个答案:

答案 0 :(得分:2)

您可以使用SelectManyToDictionary可枚举方法执行此操作: -

var result = customers.SelectMany(x => x.photoIds, (custObj, photoIds) => 
                                                         new { 
                                                                 custObj, photoIds 
                                                             })
                     .ToDictionary(x => x.photoIds, x => x.custObj.fullname);

Working Fiddle