【问题标题】:Parent and Child sorting using Lambda expression in C#在 C# 中使用 Lambda 表达式进行父子排序
【发布时间】:2015-03-04 03:35:57
【问题描述】:

我目前正在开发一个项目并使用一些 lambda 表达式(基础知识)。而且我有这个要求,我需要根据层次结构(父子)显示数据。

当前班级:

   public class Phones
    {

    public int ID { get; set; }

    public string Phone { get; set; }

    public int ChildOf { get; set; }

    }

当前数据

ID   Phone   ChildOf  
1    Samsung    0  
2    Apple     0  
3    GalaxyS3   1  
4    GalaxyS4   1  
5    5S         2  
6    iPhone 6+  2 

我期待以下结果:
结果

**Samsung**  
GalaxyS3  
GalaxyS4  
**Apple**  
5S  
iPhone6+  

【问题讨论】:

    标签: c# asp.net .net lambda


    【解决方案1】:

    您可以使用下面的 linq 执行此操作。

    var result = phoneList.Where(x=>x.ChildOf!=0).GroupBy(x=>x.ChildOf).Select(g=> new {Key = phoneList.FirstOrDefault(x=>x.ChildOf==0 && x.ID ==g.Key).Phone,Value = g.Select(x => x.Phone)});
    

    但请注意 phoneList.FirstOrDefault(x=>x.ChildOf==0) 发生这种情况只是因为您需要 Phone Name 作为分组键。

    您可以使用单独的字典来获取值并使用它。但是,如果您有父 ID,那么为什么要使用该名称。您可以在需要组密钥时使用父 ID。如果你要这样做,

    var result = phoneList.Where(x=>x.ChildOf!=0).GroupBy(x=>x.ChildOf).Select(g=> g.Key,g.ToList());
    

    当您需要在 UI 上显示时,只需将 Key 替换为匹配的父 ID。这将大大降低性能成本。

    【讨论】:

      【解决方案2】:

      这样就够了:

      var lookup = phoneData.Where(e => e.ChildOf == 0)
                                         .ToDictionary(id => id.Id, value => value.Phone);
      
      var result = phoneData.Where(e => e.ChildOf > 0)
                            .GroupBy(e => lookup[e.ChildOf])
                            .Select(g => new { Parent = g.Key, Children = g.Select(x => x.Phone) });
      

      phoneData 是您的原始数据的可枚举项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多