c# - 如何从列表中获取数据
问题描述
我在操作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");
这回答了 scott 作为技术人员总共工作了多少小时。
我将如何回答“Scott 和 Doug 作为技术人员或工程师花了多少小时?” 我在使用允许我询问 lambda 表达式的语法方面遇到困难......同样,我想知道如何在 Dict Keys 上执行“GroupBy”?
解决方案
正如其他人指出的那样,使用 aDictionary<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
推荐阅读
- c# - 包括用户控件 WPF 子元素内的触发器
- phpmyadmin - 是否可以增加 phpmyadmin textarea 中的字体大小?
- python - 有没有办法使用python交换文本文件中的两行文本?
- angular - 在新选项卡中打开 PDF 并在 Angular 中使用文件名下载
- r - 一次对多列数据框进行操作
- javascript - 如何在单击时获取数组中对象的选定值?
- node.js - 有没有办法使用 discord.js 为 Random-puppy 获取 args 来搜索该 subreddit?
- c# - ASP.NET Core 3.0 Razor 页面中的路由本地化
- android - 无法创建渐变材质设计按钮
- javascript - 使用 Javascript 做一些数学计算来计算范围