<分区>
是否可以使用单个 LINQ 查询像这样转换一维数组:
string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };
进入IEnumerable<>
包含三个属性的三个对象,从每三个连续的字符串构建?
<分区>
是否可以使用单个 LINQ 查询像这样转换一维数组:
string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };
进入IEnumerable<>
包含三个属性的三个对象,从每三个连续的字符串构建?
最佳答案
是的,有可能,您可以按数组中的索引对它们进行分组:
string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };
var result = source
.Select((element, index) => new { element, index })
.GroupBy(x => x.index / 3)
.Select(x => new
{
Id = x.ElementAt(0).element,
Name = x.ElementAt(1).element,
Value = x.ElementAt(2).element
}).ToList();
// at this stage the result variable will represent a list of 3 elements where
// each element is an anonymous object containing the 3 properties. You could of course
// replace the anonymous object with a model if you intend to use the result of the query
// outside of the scope of the method it is being executed in.
很明显,在这个例子中,没有错误检查。在运行 LINQ 查询之前,您可能会考虑这样做。显然数组的长度应该能被3整除。
关于c# - LINQ 查询以创建从字符串集合组合的对象集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20029942/