使用 LINQ 我可以将表中的数据转换为下面直接显示的格式吗? LINQ 可以执行这种类型的格式化吗?或者我应该循环遍历结果以进行格式化?
我尝试获取数据的格式:
dau gmu population year
------ ---------- ---------- -------
1 2, 201 1680 2010
2 3, 4, 5, 14 14570 2010
表中的数据:
id dau gmu population year species
----------- ----------- ----------- ------------------- ---- -------
1 1 2 1680 2010 E
2 1 201 1680 2010 E
3 2 3 14570 2010 E
4 2 4 14570 2010 E
5 2 5 14570 2010 E
6 2 14 14570 2010 E
最佳答案
实际的格式取决于您,但假设您有一个名为 list
的这些项目的集合,您可以执行以下操作:
var result = from x in list
group x by new {x.dau, x.population, x.year} into p
select new
{
dau = p.Key.dau,
population = p.Key.population,
year = p.Key.year,
gmu = p.Select (x => x.gmu)
};
如果您实际上正在处理 L2E,则可能需要将其放入内存列表中才能执行此操作。
编辑:刚刚用 L2E 尝试过,它似乎按照编写的那样工作正常。查询中的不是 list
,而是更像 context.TableName
。
这是完整的代码。输出非常草率,但已经晚了,而且我认为OP并没有那么担心格式:
var result = from x in list.Stacko1
group x by new { x.dau, x.population, x.year } into p
select new
{
dau = p.Key.dau,
population = p.Key.population,
year = p.Key.year,
gmu = p.Select(x => x.gmu)
};
result.ToList().ForEach(item=>
{
System.Console.Write("{0}\t\t", item.dau);
item.gmu.ToList().ForEach(gmuElement=>
{
System.Console.Write("{0},", gmuElement);
});
System.Console.Write("\t\t");
System.Console.Write("{0}\t\t", item.population);
System.Console.WriteLine("{0}", item.year);
});
System.Console.ReadKey();
关于asp.net-mvc - 如何使用 LINQ to Entities 将数据格式化为以下格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961684/