This question already has an answer here:
dividing a string array in groups

(1个答案)


7年前关闭。




单个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/

10-11 07:28