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

2023-09-03 13:11:47 作者:Mr.〢、低調

是否有可能是单LINQ查询可将单个维数组是这样的:

Is it possible with single LINQ query to convert a single dimensional array like this:

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

的IEnumerable<> 包含三个属性三个对象,构建起每三个连续串

into IEnumerable<> of three objects containing three properties, build from each three successive strings?

推荐答案

是的,这是可能的,你可以组到该索引数组中的:

Yes, it's possible, you could group them by the index in the array:

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整除明显

Obviously in this example, there's no error checking. It is something you might consider doing before running the LINQ query. The length of the array should be divisible by 3 obviously.