是否可以与单个 LINQ 查询像这样转换一维数组:
string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };
into 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整除。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)