LINQ查询用于创建从字符串集合组合的对象集合

时间:2013-11-17 11:11:12

标签: c# .net linq

是否可以使用单个LINQ查询来转换像这样的单维数组:

string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };

进入包含三个属性的三个对象的IEnumerable<>,从每三个连续的字符串构建?

1 个答案:

答案 0 :(得分:11)

是的,你可以用数组中的索引对它们进行分组:

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整除。