是否有可能使用单个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的倍数。