【发布时间】:2014-03-24 08:40:14
【问题描述】:
class Store
{
public int ID { get; set; }
public List<AnnualData> annualData { get; set; }
}
class AnnualData
{
public int Year { get; set; }
public Dictionary<string, double> Data { get; set; }
}
我需要获取请求的商店和请求的年份数据。我可以轻松过滤商店:
List<int> storeIDs = new List<int> {12, 13, 14};
List<Store> stores = allData.Stores.Where(s => storeIDs.Contains(s.ID)).ToList();
但我不知道如何按年份列表进一步过滤。
List<int> years = new List<int> {2012, 2013, 2014};
stores = allData.Stores.Where(s => storeIDs.Contains(s.ID)).?????
尝试了 Any/All/Contains,但我显然对 Linq 的理解不够好。提前致谢。
根据 Selmann 和 Timothy 提出的解决方案进行更新 使用您的示例,我仍然在输出中看到商店 1 的所有 3 年 - 我只想在他的案例中看到 2007 年:
static void Main(string[] args)
{
List<Store> allData = new List<Store> {
new Store { ID = 1,
annualData = new List<AnnualData> {
new AnnualData {
Year = 2006,
Data = new Dictionary<string, double>{{"Value2006", 1.0}}
},
new AnnualData {
Year = 2007,
Data = new Dictionary<string, double>{{"Value2007", 1.1}}
},
new AnnualData {
Year = 2008,
Data = new Dictionary<string, double>{{"Value2008", 1.2}}
}
}
}
};
List<int> storeIDs = new List<int> { 1 };
List<int> years = new List<int> { 2007 };
var stores = allData.Where(s => storeIDs.Contains(s.ID) &&
s.annualData.Any(x => years.Contains(x.Year)));
foreach (Store s in stores)
foreach (AnnualData a in s.annualData)
Console.WriteLine(a.Year);
}
【问题讨论】: