2016-04-29 10 views
0

の一部を上書きし、List2二つのリストを組み合わせると、私は例<code>List1</code>ため、このクラスの2つのリストを持っている値

public class SearchCriteriaOption 
{ 
    public string id { get; set; } 
    public string name { get; set; } 
    public string description { get; set; } 
    public bool selected { get; set; } 
    public bool required { get; set; } 
    public int sortOrder { get; set; } 
} 

List1常にList2よりもそれで同等またはそれ以上の項目があります。 List2はかなりList1のサブセットです

主キーは 'id'プロパティです。

私はそれがEXCEPT List1からプロパティ値を使用して、両方のリスト同じIDを持っているアイテムについてList1しかしのすべてのアイテムを持っているということなこれら二つのリストのうちの3番目のリストを作成したいですを選択してと「sortOrder」プロパティを使用する場合は、List2を使用してください。 私はこれに近づく方法を考えることができません。だから私はいくつかの助けが必要です。

+0

私はLinqを提案しています。リストに参加する方法については既に説明しています。 http://stackoverflow.com/questions/2723985/linq-join-2-listtsここでは、新しいオブジェクトを作成するために両方からプロパティを使用することに関するより詳細な情報を提供する別の投稿があります。 http://stackoverflow.com/questions/6253656/how-do-i-join-two-lists-using-linq-or-lambda-expressions – Mikanikal

答えて

2
var List3 = List1 
    .GroupJoin(List2, 
     o1 => o1.id, o2 => o2.id, 
     (option1, option2) => new { option1, option2 }) 
    .SelectMany(
     x => x.option2.DefaultIfEmpty(), 
     (x, option2) => new SearchCriteriaOption 
     { 
      // use most properties from list1 
      id = x.option1.id, 
      description = x.option1.description, 
      name = x.option1.name, 
      required = x.option1.required, 

      // using list2 for selected and sortOrder if available 
      // (if you cant use C# 6 syntax, use the next 2 lines) 
      //selected = option2 != null ? option2.selected : x.option1.selected, 
      //sortOrder = option2 != null ? option2.sortOrder : x.option1.sortOrder, 
      selected = option2?.selected ?? x.option1.selected, 
      sortOrder = option2?.sortOrder ?? x.option1.sortOrder, 
     }) 
    .ToList(); 
+0

UnionまたはJoinにする必要がありますか?この例ではList3に2つのアイテムがありますが、List1のメインリストには10​​個のアイテムがあり、List2には2個のアイテムがあるため、10個のアイテムが必要です。 – Bohn

+1

申し訳ありませんが、私は "両方のリストに同じIDを持つアイテム"の3番目のリストを作成したかったとお伝えしました。私の悪い、私はそれを修正します。 – Xiaoy312

+1

@Bone私は内部結合を左結合に変更しました – Xiaoy312

関連する問題