英文:
Convert a List<object[]> to List<object> where the count of object[] is dynamic
问题
如何将 List<object[]>
转换为 List<object>
,其中 object[]
中的对象数量是动态的(在单个集合中,对象数量相同,即 items[0].count
等于 items[1].count
,但每个不同的集合可以具有不同数量的对象数量)。
到目前为止,我尝试的方法是,如果项目的数量是恒定的,可以通过以下代码实现:
dt.Select().Select(s => s.ItemArray).Select(s => new {a = s[0], b= s[1]}..).ToList()
但如何为动态数量的列生成选择语句呢?
更多关于动态列数量的背景信息:
List<object[]>
是从 dataRows
生成的。它之所以是动态的,是因为 dataTable
可能具有任意数量的列。
任何建议都将有助于解决问题。
英文:
How could we convert a List<object[]>
to List<object>
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).
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 => s.ItemArray).Select(s => 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<object[]>
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<object[]> objectArrays = ...
List<object> flattenedObjects = objectArrays.SelectMany(arr => 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<object> allFields = dt.AsEnumerable()
.SelectMany(row => row.ItemArray)
.ToList();
If you want the most efficient approach:
List<object> allFields = new(dt.Rows.Count * dt.Columns.Count);
foreach(DataRow row in dt.Rows) allFields.AddRange(row.ItemArray);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论