我有一个Object,MyRoot
带有DateTime和List。我如何使用WHERE语句缩小列表范围,但仍然返回MyRoot
和列表以缩小结果?
这是我的课程:
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
rateList
Type = "B"
之前返回{{1}}对象感谢您的帮助!
答案 0 :(得分:1)
根据您的问题,我认为您需要更改模型以创建Rate属性作为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; }
}
这里的主要方法应该是
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();
}
答案 1 :(得分:0)
var myFilteredList = rateList.Where(x=> x.Type == "B");
就是这样。 Where是一个lambda表达式,它返回集合中具有Type = B的任何内容。
答案 2 :(得分:0)
var myRoot = new MyRoot { RatesAsOf = "2016-11-09", Rates = ratesList.Where(r=>r.Type == "B") };
你真的需要阅读LINQ。这是基本的东西。
答案 3 :(得分:0)
试试这个:
var myRoot = new MyRoot {RatesAsOf =“2016-11-09”,Rates = ratesList};
var myRoot1 = new MyRoot {LastUpdated = myRoot.LastUpdated,Rates = myRoot.Rates.Where(x =&gt; x.Type ==“A”)。ToList()};