2016-11-09 101 views
-2

我有一個對象,帶有DateTime和List的對象MyRoot。我如何使用WHERE語句來縮小列表的範圍,但是還會返回MyRoot和帶有縮小結果的列表?使用列表返回對象但使用WHERE篩選列表

這裏是我的課:

public class MyRoot 
{ 
    public DateTime LastUpdated { get; set; } 
    public MyRates Rates { get; set; } 
} 

public class MyRates 
{ 
    public string Type { get; set; } 
    public string Rate { get; set; } 
} 

示例代碼:

var rateList = new List<MyRates>() { 
    new MyRate { Type = "A", Program = "ABC", Rate = "1.0" }, 
    new MyRate { Type = "B", Program = "DEF", Rate = "1.5" }, 
    new MyRate { Type = "B", Program = "XYZ", Rate = "2.5" }, 
}; 

var myRoot = new MyRoot { RatesAsOf = "2016-11-09", Rates = ratesList }; 

問題:我想不通我怎麼能返回myRoot對象,其中的rateListType = "B"感謝您的幫助!

+0

屬性'價格'不是一個列表。因此不允許將'rateList'分配給'Rates'。 –

+0

您的MyRoot類的房價不屬於列表,您是否可以編輯您的問題? – Zinov

+1

您已將'MyRoot.Rates'定義爲'Public MyRates',但您正嘗試將其分配給'List '。我不認爲編譯器會讓你變得非常遠。 – clarkitect

回答

0
var myFilteredList = rateList.Where(x=> x.Type == "B"); 

那就是它。在哪裏是一個lambda表達式,其集合中返回任何有TYPE = B.

0
var myRoot = new MyRoot { RatesAsOf = "2016-11-09", Rates = ratesList.Where(r=>r.Type == "B") }; 

你真的需要在LINQ閱讀起來。這是基本的東西。

+2

費率不是一個清單,直到OP修復他的模型後才能使用。 – clarkitect

+0

好的。我也注意到他的MyRoot類沒有名爲RatesAsOf的屬性。此代碼的各種問題。 – Spivonious

0

嘗試這種情況:

變種myRoot =新MyRoot {RatesAsOf = 「2016年11月9日」,價格= ratesList}; var myRoot1 = new MyRoot {LastUpdated = myRoot.LastUpdated,Rates = myRoot.Rates.Where(x => x.Type ==「A」)。ToList()};}}

1

根據您的問題,我想你需要改變你的模型來創建價格財產MyRates的列表,並添加屬性計劃過於

public class MyRoot 
    { 
     public DateTime LastUpdated { get; set; } 
     public List<MyRates> Rates { get; set; } 
    } 

public class MyRates 
{ 
    public string Type { get; set; } 

    public string Rate { get; set;} 
    public string Program { get; set; } 
} 

這裏就像是Main方法看起來應該

 static void Main(string[] args) 
     { 
      var rateList = new List<MyRates>() 
      { 
       new MyRates {Type = "A", Program = "ABC", Rate = "1.0"}, 
       new MyRates {Type = "B", Program = "DEF", Rate = "1.5"}, 
       new MyRates {Type = "B", Program = "XYZ", Rate = "2.5"}, 
      }; 

      var myRoot = new MyRoot { LastUpdated = DateTime.Parse("2016-11-09"), Rates = rateList }; 

      var list = rateList.Where(x => x.Type == "B"); 

      //OR try to create a new object 
      myRoot = new MyRoot {LastUpdated = myRoot.LastUpdated, Rates = myRoot.Rates.Where(x => x.Type == "B").ToList() }; 


      Console.ReadLine(); 
     }