我在操纵List<Dictionary<string,string>>> SSRList
以便轻松获取数据方面遇到麻烦。我已经走了这么远:
var bleh = SSRList
.Where(x => x.ContainsKey("ServiceTechHrs")) //Scott Shauf total tech hours
.Where(x => x.ContainsKey("ServiceTech") && x.ContainsValue("Scott Shauf"))
.Select(x => x["ServiceTechHrs"])
.Where(x => x != "")
.Sum(x => Convert.ToDouble(x))
.Dump("All Scott Shauf TechNumbers");
这回答了斯科特作为技术员总共工作了多少小时。
我将如何回答“斯科特和道格担任技术员或工程师花费了几个小时?”我在语法上遇到了麻烦,可以让我询问lambda表达式...同样,我想知道如何在Dict Keys上执行“ GroupBy”?
答案 0 :(得分:0)
正如其他人指出的那样,使用Dictionary<string, string>
表示某种结构化类型会使您摆脱LINQ的全部魅力。但是,如果由于某些(可疑的)设计原因而不得不走这条路,那么尽快进行强类型输入将使它返回。
您似乎想使用类似的东西
public interface ITechnician
{
string ServiceTech { get; }
double ServiceTechHours { get; } // or should it be TimeSpan?
}
我会写一些代码来完成肮脏的工作:
public static class MyExtensions
{
public static IEnumerable<ITechnician> OfTypeTechnician(this IEnumerable<IDictionary<string, string>> records)
{
foreach (var record in records)
{
if (!record.TryGetValue("ServiceTech", out var serviceTech)) continue;
if (!record.TryGetValue("ServiceTechHrs", out var serviceTechHrsStr) || !double.TryParse(serviceTechHrsStr, out var serviceTechHrs)) continue;
yield return new Technician { ServiceTech = serviceTech, ServiceTechHours = serviceTechHrs };
}
}
private class Technician : ITechnician
{
public string ServiceTech { get; set; }
public double ServiceTechHours { get; set; }
}
}
休息很简单:
var records = new[]
{
new Dictionary<string, string> { { "ServiceTech", "Scott Shouf"}, { "ServiceTechHrs", "4711" } },
new Dictionary<string, string> { { "ServiceTech", "Scott Shouf"}, { "ServiceTechHrs", "0815" } },
new Dictionary<string, string> { { "ServiceTech", "Scott Shouf"}, { "ServiceTechHrs", "not convertible to double" } },
new Dictionary<string, string> { { "ServiceTech", "Someone Else"}, { "ServiceTechHrs", "42" } },
new Dictionary<string, string> { { "Animal", "Giraffe" } }
};
var allScottShaufTechNumbers = records
.OfTypeTechnician()
.Where(t => t.ServiceTech == "Scott Shouf")
.Sum(t => t.ServiceTechHours);
// 5526