LINQ:转换扁平结构分层 [英] Linq: Converting flat structure to hierarchical

查看:131
本文介绍了LINQ:转换扁平结构分层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是转换一个平面结构最简单,有些有效的方式:

 对象[] [] RAWDATA =新的对象[] [] 
{
{A1,B1,C},
{A1,B1,C 2},
{ A2,B2,C},
{A2,B2,C4}
// ..更多
};



成层次结构:

 类X 
{
公共X()
{
CS =新的List<串GT;();
}
公共字符串A {搞定;组; }
公共字符串B {搞定;组; }
公开名单<串GT; CS {搞定;私人集; }
}



结果应该是这样的。



  //伪代码描述结构:
结果=
{
新的X(){a =A1,b =B1,CS = {C1,C2}},
新的X(){a =A2,b =B2,CS = {C3,C4} }
}

最好使用LINQ扩展方法。目标类 X 可以改变(如公共setter方法列表),只有当不可能/有用,因为它是现在。


< DIV CLASS =h2_lin>解决方案

对于这种特殊情况:

  .GroupBy(X = >新建{A = X [0],b = X [1]})
。选择(X =>新建{A = x.Key.a,b = x.Key.b,C = x.Select(C => C [2])})


What is the easiest and somewhat efficient way to convert a flat structure:

object[][] rawData = new object[][] 
{ 
  { "A1", "B1", "C1" }, 
  { "A1", "B1", "C2" },
  { "A2", "B2", "C3" }, 
  { "A2", "B2", "C4" }
  // .. more 
};

into a hierarchical structure:

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; }
}

the result should look like this

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

Preferably using Linq extension methods. Target class X could be changed (eg. a public setter for the List), only if not possible / useful as it is now.

解决方案

for this particular case:

   .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] ) })

这篇关于LINQ:转换扁平结构分层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆