LINQ查询以创建一个对象集合,该集合由字符串集合组合而成

6

是否有可能使用单个LINQ查询将这样一个一维数组转换如下:

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

将每三个连续的字符串构建成包含三个属性的三个对象的 IEnumerable<> 类型?

2
如果可能的话,我想看看它;代码将会非常漂亮。 - frenchie
参考一下,一些相关问题可以在https://dev59.com/fnM_5IYBdhLWcg3wp00X和https://dev59.com/VHRA5IYBdhLWcg3wsgLq找到。 - Stuart Golodetz
1个回答

12

是的,这是可能的,您可以按数组中的索引将它们分组:

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的倍数。


1
显然,它将按原样投入生产 :) - Johann Blais
嗯,我只是提一下,因为我看到很多人从SO复制粘贴到他们的生产代码中(包括我自己) :-) - Darin Dimitrov
是的,Darin,但你看看这段代码有多美...这就是艺术。 - Marco
真是太棒了! - frenchie
+1 - 因为您已经回答了20000个问题!其中几个是我的。 - P.Brian.Mackey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接