合并对象属性与LINQ名单 [英] Combine object properties into a list with LINQ

查看:90
本文介绍了合并对象属性与LINQ名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有性能NUM1,NUM2,NUM3的目标x。我想借此_对象的列表,并创建填充了NUM1,NUM2,NUM3值单个整数列表

Say I have properties num1, num2, num3 on objectX. I want to take a list of objectX and create a single list of integers populated with the num1, num2, num3 values.

下面是一个使用System.Drawing.Point一个例子:

Here's an example using System.Drawing.Point:

Point p1 = new Point(1,2);
Point p2 = new Point(3,4);

var points = new[] { p1, p2 };
var combined = points.SelectMany(a => new[] {a.X, a.Y});

这是这样做的最易读的方式?语法感觉有点繁琐给我。你可以用 LINQ查询表达式办呢?

Is this the most readable way of doing this? The syntax feels a bit fiddly to me. Could you do it with a LINQ Query expression?

仅供参考用在这个例子中LBushkin的查​​询表达式应该是这样的:

FYI using LBushkin's query expression in this example would look like this:

var combined = from p in points
    let values = new[] {p.X, p.Y}
    from x in values
    select x;       



我会离开它的读者练习来决定哪个更具有可读性。

I'll leave it an exercise for the reader to decide which is more readable.

推荐答案

这是一个例子,我可能会使用查询语法与LINQ:

var result = from item in someList
             let values = new int[]{ item.A, item.B, item.C, ... }
             from x in values
             select x;



使用自定义迭代(如柯克演示)可以是更有效的,因为它不要求分配临时数组 - 但CLR是回收短期对象比较好,所以在实践中这很少有问题

Using a custom iterator (as Kirk demonstrates) may be more efficient, since it doesn't require allocating the temporary array - but the CLR is relatively good at recycling short-lived objects, so in practice this is rarely an issue.

这篇关于合并对象属性与LINQ名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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