2017-07-14 5 views
-2

以下のコードは値を返していません。私は残高が$ 0以下の顧客名と残高を印刷しようとしています。私の財産は正しい方法ではないと信じています。私はオブジェクト指向プログラミングとLINQを初めて使用しています。どんな助けにも感謝します。C#のプロパティ、コンストラクタ、およびLINQで問題が発生しました

namespace LinqExample 
{ 
    class Customer 
    { 
     private string name, phone, address; 
     private int balance; 
     public string custData; 

     public string Name 
     { 
      get { return name; } 
      set { name = value; } 
     } 

     public string Phone 
     { 
      get { return phone; } 
      set { phone = value; } 
     } 

     public string Address 
     { 
      get { return address; } 
      set { address = value; } 
     } 

     public int Balance 
     { 
      get { return balance; } 
      set { balance = value; } 
     } 

     public Customer(string name, string phone, string address, int balance) 
     { 
      custData = name + phone + address + balance; 
     } 
    } 
} 

namespace LinqExample 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<Customer> customers = new List<Customer>(); 

      customers.Add(new Customer("Amit", "123-456-789", "123 Any Road", 25)); 
      customers.Add(new Customer("Ajay", "571-888-1234", "1234 Any Street", 50)); 
      customers.Add(new Customer("John", "707-123-4560", "456 John Street", -10)); 
      customers.Add(new Customer("Ashley", "707-123-8402", "789 Ashley Street", -20)); 

      var overdue = 
       from cust in customers 
       where cust.Balance < 0 
       orderby cust.Balance ascending 
       select new { cust.Name, cust.Balance }; 

      foreach (var cust in overdue) 
      { 
       Console.WriteLine($"Name = {cust.Name}, Balance = {cust.Balance}"); 
      } 

     } 
    } 
} 
+1

これらのプロパティには値は設定されていません。 – Nilay

答えて

4

あなたはメンバーの値を設定する必要があります。他の人はあなたがCTOR値で渡さにあなたのプロパティのいずれかを割り当てていない述べている

public Customer(string name, string phone, string address, int balance) 
    { 
     this.name = name; 
     this.phone = phone; 
     this.address = address; 
     this.balance = balance; 
     custData = name + phone + address + balance; 
    } 
1

"custdata"以外のプロパティを設定していない場合は、残りのプロパティもコンストラクタで設定する必要があります。

0

通り。 Romanoが提案したか、オブジェクト初期化子を使用してください。

コンストラクタにプロパティを割り当てます。デフォルトCTORと

​​

オブジェクトInitilizer。サイドノートとして

customers.Add(new Customer 
{ 
    Name = "Bill", 
    Phone = "555-555-5555", 
    Address = "2345 Some street", 
    Balance = "100000000" 
}); 

、代わりに公共の場「CUSTDATA」はその連結データのすべてを返すようにToStringメソッドをオーバーライドしてみてくださいすることを使用しての。

関連する問題