,c#,linq,dictionary,lambda"/>

首页 > 解决方案 > 如何从列表中获取数据

问题描述

我在操作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”?

标签: c#linqdictionarylambda

解决方案


正如其他人指出的那样,使用 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

推荐阅读