Linq grouping from Category to subcategory

时间:2016-12-02 05:00:00

标签: c# asp.net-mvc linq c#-4.0

I have list of data. Eg.

| Id | Name | GroupId | GroupName |
|----|------|---------|-----------|
| 1  | nm1  | 1       | Group1    |
| 2  | nm2  | 1       | Group1    |
| 3  | nm3  | 1       | Group1    |
| 4  | nm4  | 2       | Group2    |
| 5  | nm5  | 2       | Group2    |

{ id = 1, Name = "nm1", GroupId = 1, GroupName = "Group1" }
{ id = 2, Name = "nm2", GroupId = 1, GroupName = "Group1" }

I would like the result list to have the Id, Name only. Id from GroupId becomes -1. A empty value with Id -1 is also needed. (blank)

| Id | Name      |
|----|-----------|
| -1 | Group1    |
| 1  | nm1       |    
| 2  | nm2       |   
| 3  | nm3       |        
| -1 | blank     |
| -1 |  Group2   | 
| 4  |  nm4      | 
| 5  |  nm5      | 

Is it possible?

1 个答案:

答案 0 :(得分:1)

我认为您必须首先对数据进行分组,然后重新组织如下数据。

如下所示的课程

 public class GroupData
{
    public int Id { get; set; }
    public String Name { get; set; }
    public int GroupId { get; set; }
    public String GroupName { get; set; }
}

public class Result
{
    public int Id { get; set; }
    public String Name { get; set; }
}

逻辑看起来像

//添加数据

List<GroupData> dataList = new List<GroupData>();

        dataList.Add(new GroupData() {Id = 1, Name = "nm1", GroupId = 1, GroupName = "Group1"});
        dataList.Add(new GroupData() { Id = 2, Name = "nm2", GroupId = 1, GroupName = "Group1" });
        dataList.Add(new GroupData() { Id = 3, Name = "nm3", GroupId = 1, GroupName = "Group1" });
        dataList.Add(new GroupData() { Id = 4, Name = "nm4", GroupId = 2, GroupName = "Group2" });
        dataList.Add(new GroupData() { Id = 5, Name = "nm5", GroupId = 2, GroupName = "Group2" });

//对数据进行分组

        var result =
        (from data in dataList
            group data by data.GroupName
            into newGroup
            orderby newGroup.Key
            select newGroup);

重新安排您所需的格式

 var items=new List<Result>();
        foreach (var item in result)
        {
            items.Add(new Result {Id=-1, Name=item.Key});
            items.AddRange(item.ToList().Select(subItem => new Result {Id = subItem.Id, Name = subItem.Name}));
            //You can add your blank record here. but not sure exact logic 
        }