要编写LINQ查询以进行结果的透视,可以使用GroupBy和SelectMany方法来实现。
下面是一个示例代码,演示如何使用LINQ查询来对数据进行透视:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
// 创建示例数据
List people = new List()
{
new Person { Name = "John", Age = 30, City = "New York" },
new Person { Name = "Jane", Age = 25, City = "London" },
new Person { Name = "Mike", Age = 40, City = "New York" },
new Person { Name = "Lisa", Age = 35, City = "London" },
new Person { Name = "David", Age = 45, City = "New York" }
};
// 使用LINQ查询进行透视
var result = people
.GroupBy(p => p.City) // 按城市进行分组
.SelectMany(g => g.Select(p => new { City = g.Key, Name = p.Name, Age = p.Age })) // 展开分组并选择相应的属性
.OrderBy(p => p.City); // 按城市排序
// 输出结果
foreach (var person in result)
{
Console.WriteLine($"City: {person.City}, Name: {person.Name}, Age: {person.Age}");
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
}
在上面的示例中,我们首先创建了一个包含Person对象的列表。然后,我们使用LINQ查询对这些人按城市进行分组。接下来,我们使用SelectMany方法来展开每个分组,并选择相应的属性。最后,我们使用OrderBy方法按城市对结果进行排序。最后,我们将结果打印到控制台上。
上述代码的输出如下:
City: London, Name: Jane, Age: 25
City: London, Name: Lisa, Age: 35
City: New York, Name: John, Age: 30
City: New York, Name: Mike, Age: 40
City: New York, Name: David, Age: 45
这个例子演示了如何使用LINQ查询对结果进行透视,按城市分组并展开相应的属性。您可以根据自己的需求修改代码来适应不同的数据结构和透视需求。