c# – Linq:将平面结构转换为分层结构

前端之家收集整理的这篇文章主要介绍了c# – Linq:将平面结构转换为分层结构前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
转换平面结构最简单有效的方法是什么?
object[][] rawData = new object[][] 
{ 
  { "A1","B1","C1" },{ "A1","C2" },{ "A2","B2","C3" },"C4" }
  // .. more 
};

成层次结构:

class X
{
  public X () 
  {
    Cs = new List<string>();
  }
  public string A { get; set; }
  public string B { get; set; }
  public List<string> Cs { get; private set; }
}

结果应该是这样的

// pseudo code which describes structure:
result =
{
  new X() { A = "A1",B = "B1",Cs = { "C1","C2" } },new X() { A = "A2",B = "B2",Cs = { "C3","C4" } }
}

最好使用Linq扩展方法.目标类X可以被更改(例如,列表的公共设置器),只有当现在不可能/有用时.

解决方法

对于这种特殊情况:
.GroupBy( x => new { a = x[0],b = x[1] } )
   .Select( x => new { A = x.Key.a,B = x.Key.b,C = x.Select( c => c[2] ) })

猜你在找的C#相关文章