c# - LINQ 查询以创建从字符串集合组合的对象集合

标签 c# .net linq

<分区>

是否可以使用单个 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/

相关文章:

.net - 是否有内置的名称/值对属性?

c# - `1 在 LINQ 中代表什么?

c# - List<DateTime> 上的 Any() 方法未按预期工作

c# - 无法使用空对象调用扩展方法

c# - 需要 C# 代码使用 DataReader 从 Microsoft Access Attachment 数据类型读取多个附件

c# - EPPlus 生成的 Excel 已损坏

c# - C# 中的空 "if"语句是否会导致错误或警告?

.net - IEnumerable<> 上的 First() 和 Last() 真的是第一个和最后一个吗?

c# - 如何取消以编程方式添加的菜单的垂直空间?

c# - .Net TraceSource/TraceListener 框架是否有类似于 log4net 的 Formatters 的东西?