将一个List<object[]>转换为List<object>,其中object[]的数量是动态的。

huangapple go评论56阅读模式
英文:

Convert a List<object[]> to List<object> where the count of object[] is dynamic

问题

如何将 List&lt;object[]&gt; 转换为 List&lt;object&gt;,其中 object[] 中的对象数量是动态的(在单个集合中,对象数量相同,即 items[0].count 等于 items[1].count,但每个不同的集合可以具有不同数量的对象数量)。

示例数据:
将一个List<object[]>转换为List<object>,其中object[]的数量是动态的。

到目前为止,我尝试的方法是,如果项目的数量是恒定的,可以通过以下代码实现:

dt.Select().Select(s =&gt; s.ItemArray).Select(s =&gt; new {a = s[0], b= s[1]}..).ToList()

但如何为动态数量的列生成选择语句呢?

更多关于动态列数量的背景信息:
List&lt;object[]&gt; 是从 dataRows 生成的。它之所以是动态的,是因为 dataTable 可能具有任意数量的列。

任何建议都将有助于解决问题。

英文:

How could we convert a List&lt;object[]&gt; to List&lt;object&gt; where the count of objects in object[] is dynamic(in a single collection it is the same i.e. items[0].count is equal to items[1].count but every different collection could have a dynamic number of item count).

Sample Data:
将一个List<object[]>转换为List<object>,其中object[]的数量是动态的。

What I tried so far is if the count of items is constant it can be achieved by the below code

dt.Select().Select(s =&gt; s.ItemArray).Select(s =&gt; new {a = s[0], b= s[1]}..).ToList()  

But how could we generate the select statement for the dynamic number of columns?

More background on having the dynamic number of columns:
The List&lt;object[]&gt; is generated from dataRows. The reason it is dynamic is because dataTable could have any number of columns.

Any suggestion will be helpful

答案1

得分: 2

`SelectMany` 是你需要的,然后不管每个数组中包含多少项都不重要:

    List<object[]> objectArrays = ...
    List<object> flattenedObjects = objectArrays.SelectMany(arr => arr).ToList(); 

然而,根据你的截图,我可以看到你有一个 `DataTable`,你想要获取所有行中的所有字段的列表,那么最好使用以下方法:

    List<object> allFields = dt.AsEnumerable()
      .SelectMany(row => row.ItemArray)
      .ToList();

如果你想要最高效的方法:

    List<object> allFields = new List<object>(dt.Rows.Count * dt.Columns.Count);
    foreach(DataRow row in dt.Rows) allFields.AddRange(row.ItemArray);
英文:

SelectMany is what you need, then it doesn't matter how many items are contained in each array:

List&lt;object[]&gt; objectArrays = ...
List&lt;object&gt; flattenedObjects = objectArrays.SelectMany(arr =&gt; arr).ToList(); 

However, in your screenshot i can see that you have a DataTable and you want a list of all fields in all rows, then better use:

List&lt;object&gt; allFields = dt.AsEnumerable()
  .SelectMany(row =&gt; row.ItemArray)
  .ToList();

If you want the most efficient approach:

List&lt;object&gt; allFields = new(dt.Rows.Count * dt.Columns.Count);
foreach(DataRow row in dt.Rows) allFields.AddRange(row.ItemArray);

huangapple
  • 本文由 发表于 2023年6月15日 21:36:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定