LINQ按结果属性拆分和分组

时间:2013-07-30 07:57:23

标签: linq split group-by

我有一个对象,该对象的一个​​属性是以逗号分隔的名称列表,例如

IList<Audits> auditData = new List<Audits>();
auditData.Add(new Audit
              {
                  Auditors = "Adam West, George Best",
                  TimeSpent = 7
              });

auditData.Add(new Audit
              {
                  Auditors = "Adam West",
                  TimeSpent = 5
              });

auditData.Add(new Audit
              {
                   Auditors = "Adam West, George Best, Elvis Presley",
                   TimeSpent = 3
              });

我想使用LINQ来查询这些数据,分割审核员属性,按审核员分组,以及每个审核员的总时间总和,给我一份审核员列表,每个审核员花费时间,例如

。 Adam West 15,
George Best 10,
埃尔维斯普雷斯利3

任何人都可以协助我这样做吗?感谢。

3 个答案:

答案 0 :(得分:2)

使用lambdas:

var results =
    auditData
        // Flatten list - to list of individual auditors and time spent
        .SelectMany(
            audit => audit.Auditors.Split(',').Select(s => s.Trim()),
            (audit, auditorName) => new
            {
                Auditor = auditorName,
                TimeSpent = audit.TimeSpent,
            })
        // Group by auditor name
        .GroupBy(a => a.Auditor)
        // Sum time spent
        .Select(auditorGroup => new
        {
            Auditor = auditorGroup.Key,
            TotalTimeSpent = auditorGroup.Sum(a => a.TimeSpent)
        })
        .ToList();

答案 1 :(得分:1)

这应该做你想要的:

var query =
    from a in auditData
    let auditors = a.Auditors.Split(',').Select(s => s.Trim())
    from au in auditors
    group a.TimeSpent by au into g
    select new { Auditor = g.Key, TimeSpent = g.Sum() };

答案 2 :(得分:1)

var res = auditData.Select(audit => audit.Auditors.Split(',').ToDictionary(a => a, a => audit.TimeSpent))
            .SelectMany(a => a)
            .GroupBy(a => a.Key)
            .ToDictionary(g => g.Key, s => s.Sum(g => g.Value));

首先拆分字符串并转换为键值对。然后将词典拼成一个单词。然后分组并加总。