使用Linq重新排列表数据

时间:2015-08-16 04:12:38

标签: c# .net linq

我的数据格式如下:

(Table: Hours)
{ Date = "21/04/2008", Person = Sally, Hours= 3 }
{ Date = "21/04/2008", Person = Sam, Hours = 15 }
{ Date = "22/04/2008", Person = Sam, Hours = 8 }
{ Date = "22/04/2008", Person = Sally, Hours = 9 }

数据类型:日期=日期,人=字符串,小时=整数

使用LINQ我想选择这种格式:

{ Date = "21/04/2008", Sam = 15, Sally = 3 }
{ Date = "22/04/2008", Sam = 8, Sally = 9 }

数据类型:日期=日期,山姆=整数,莎莉=整数

这可能吗?

2 个答案:

答案 0 :(得分:6)

from d in data
group d by d.Date into g
select new {Date = g.Key, People = g.Select(gg=>new{Person = gg.Person, Hours = gg.Hours})}

这将为您提供数据,然后只是格式化以便正确显示。

答案 1 :(得分:2)

据我了解,您有一张表格,记录每位员工在特定数据中工作的小时数。我假设它可以包含一天中一个人的多个日志。如果您不想使用LINQ,可以使用此

var hours = new[] {
                        new { Date = "21/04/2008", Person = "Sally", Hours= 3 },
                        new { Date = "21/04/2008", Person = "Sam", Hours = 15 },
                        new { Date = "22/04/2008", Person = "Sam", Hours = 8 },
                        new { Date = "22/04/2008", Person = "Sally", Hours = 9 },
                        new { Date = "22/04/2008", Person = "John", Hours = 5 },
                        new { Date = "22/04/2008", Person = "John", Hours = 2 },
                        new { Date = "22/04/2008", Person = "Tom", Hours = 9 },
                   };


var result = new Dictionary<string, Dictionary<string, int>>();
foreach (var workLog in hours)
{
    if (!result.ContainsKey(workLog.Date))
        result[workLog.Date] = new Dictionary<string, int>();

    if (!result[workLog.Date].ContainsKey(workLog.Person))
        result[workLog.Date][workLog.Person] = 0;

    result[workLog.Date][workLog.Person] += workLog.Hours;
}

Console.WriteLine(JsonConvert.SerializeObject(result));

,结果是

  

{&#34; 21/04/2008&#34; {&#34;萨利&#34;:3,&#34;萨姆&#34;:15}&#34; 22/04/2008& #34; {&#34;萨姆&#34;:8,&#34;萨利&#34;:9,&#34;约翰&#34;:7,&#34;汤姆   &#34;:9}}