LINQ查询创建对象从字符串的集合组合的集合 [英] LINQ query to create a collection of objects combined from a collection of strings

查看:133
本文介绍了LINQ查询创建对象从字符串的集合组合的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能是单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.

这篇关于LINQ查询创建对象从字符串的集合组合的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆