2017-11-23 10 views
-2

ここに私のクエリ結果とクラス、私はリストに「顧客」のリストオブジェクトを作成する方法のリストが欲しい「契約」プロパティですクエリ結果からリストオブジェクトを作成しますか?

customer contract_id number_of_products 
1  HD2   1000 
1  HD3   4500 
1  HD4   20000 
2  HD5   70 
2  HD6   8000 
3  HD7   660 
3  HD8   2200 



    public class customer 
    { 
     public string customer { get; set; } 
     public List<contract> ls_contract{ get; set; } 
    } 
    public class contract 
    { 
     public string contract_id{ get; set; } 
     public string number_of_products { get; set; } 
    } 
+0

質問は何ですか? –

+0

https://stackoverflow.com/help/mcveサンプル入力データを入力する少しのサンプルプログラムを書いてください。次に、その入力データに基づいて受信する予定の出力を指定します。 – mjwills

+0

あなたが持っている実際のJSON形式は何ですか(あなたのデータがDB表のように見えるにもかかわらず、少なくともjsonにタグ付けされていますか?何を試してみましたか..ヒント 'GroupBy' –

答えて

2

まずあなたがC#のコーディング規約に従う必要があり:

public class Customer 
{ 
    public string Name { get; set; } 
    public List<Contract> Contracts { get; set; } 
} 

public class Contract 
{ 
    public string Id { get; set; } 
    public string NumberOfProducts { get; set; } 
} 

クエリ結果を読み取るには、フラットなデータ構造が必要です。

private class CustomerContract 
{ 
    public string CustomerName { get; set;} 
    public string ContractId { get; set;} 
    public int NumberOfProducts { get; set;} 
} 

結果セットをフラットなデータ構造体に読み込んだら、顧客IDごとにグループ化し、必要なデータ構造に変換することができます。

var result = customerContract.GroupBy(item => item.CustomerName) 
          .Select(group => new Customer { 
                Name = group.CustomerName, 
                Contracts = group.Select(
                 e => new Contract { 
                  Id = e.ContractId, 
                  NumberOfProducts = e.NumberOfProducts 
                 } 
               ).ToList() 
               }) 
          .ToList(); 
+1

これは正しいかもしれませんが、努力が終わっても答えを投稿するのは残念ですが、DBやjsonファイルを照会しているかどうかは分かりません。 –

+0

それは恥です私はconfcheする必要があります –

1
あなたが作成し、として顧客のリストを作成することができ

List<Customer> lstCustomer = new List<Customer>() 
      { 
       new Customer(){customer="1", ls_contract=new List<Contract>() 
       { 
        new Contract(){contract_id="HD2", number_of_products="1000"}, 
        new Contract(){contract_id="HD3", number_of_products="4500"}, 
        new Contract(){contract_id="HD4", number_of_products="20000"} 
       } }, 
       new Customer(){customer="2", ls_contract=new List<Contract>() 
       { 
        new Contract(){contract_id="HD5", number_of_products="70"}, 
        new Contract(){contract_id="HD6", number_of_products="8000"}, 
       } }, 
       new Customer(){customer="3", ls_contract=new List<Contract>() 
       { 
        new Contract(){contract_id="HD7", number_of_products="660"}, 
        new Contract(){contract_id="HD8", number_of_products="2200"}, 
       } } 


      }; 
+0

注:クラス名は "Customer"と "Contract" ==>として書くクラス名はメンバー名と異なる必要があります –

関連する問題