4

IdとInformationという2つの共通の属性を共有する2つのクラスがあります。

public class Foo
{
     public Guid Id { get; set; }

     public string Information { get; set; }

     ...
}
public class Bar
{
     public Guid Id { get; set; }

     public string Information { get; set; }

     ...
}

LINQを使用して、Fooオブジェクトの入力リストとBarオブジェクトの入力リストを取得するにはどうすればよいですか。

var list1 = new List<Foo>();
var list2 = new List<Bar>();

そして、それぞれのIDと情報を1つの辞書にマージします。

var finalList = new Dictionary<Guid, string>();

前もって感謝します。

4

2 に答える 2

8

あなたができるように聞こえます:

// Project both lists (lazily) to a common anonymous type
var anon1 = list1.Select(foo => new { foo.Id, foo.Information });
var anon2 = list2.Select(bar => new { bar.Id, bar.Information });

var map = anon1.Concat(anon2).ToDictionary(x => x.Id, x => x.Information);

(これらすべてを1つのステートメントで実行できますが、この方法の方が明確だと思います。)

于 2012-07-25T17:49:11.520 に答える
0
   var finalList = list1.ToDictionary(x => x.Id, y => y.Information)
            .Union(list2.ToDictionary(x => x.Id, y => y.Information))
                        .ToDictionary(x => x.Key, y => y.Value);

IDが一意であることを確認してください。そうでない場合は、最初の辞書によって上書きされます。

編集:.ToDictionary(x => x.Key、y => y.Value);を追加しました。

于 2012-07-25T17:48:26.463 に答える