LINQ: how to transform list by performing calculat

2019-07-10 03:51发布

I have a class

Class MyObject
{
    decimal v1;
    decimal dv1;
    decimal v2;
    decimal dv2;
}

and a

List<MyObject> ...

I need to process every element of the list by adding dv1 to v1 and dv2 to v2 Something like (pseudo-syntax):

myList.Transform(o=>o.v1+=o.dv1, o.v2+=o.dv2)

How can I do this (obvious my pseudo-syntax doesn't works)?

Thank you

5条回答
等我变得足够好
2楼-- · 2019-07-10 04:03

LINQ offers 'select' for transformation

list.Select( obj => new MyObject(obj.v1 + obj.dv1, obj.dv1, obj.v2 + obj.dv2, obj.dv2))

But be aware that the return value is a new list ; the elements of the original list are not modified. No Side effects/State mutation. If that is your goal, go for select ; else go with the for/for-each as others have suggested.

查看更多
我只想做你的唯一
3楼-- · 2019-07-10 04:05

Thanks for all answers. I was thinking linq can provide an elegant way, but you are right - foreach does the job just right.

查看更多
迷人小祖宗
4楼-- · 2019-07-10 04:06

I don't think this is typical task for linq, but if you want, you can do this:

List<MyClass> objects = GetMyClasses();
Func<Action<MyClas>s, bool> do = (action) => { action(); return true; }
(from o in objects
 where do( o, b=> { b.v1 += b.dv1; b.v2 += b.dv2; } )
 select o).ToArray();
查看更多
在下西门庆
5楼-- · 2019-07-10 04:18

You can use the List's ForEach method:

List<MyObject> objects = new List<MyObject>();

// Populate list.

objects.ForEach(obj => {
  obj.v1 += obj.dv1;
  obj.v2 += obj.dv2;
});
查看更多
来,给爷笑一个
6楼-- · 2019-07-10 04:22

LINQ is made to get a subset of a given enumeration or to create an enumeration with new types out of an list.

To manipulate a given list, LINQ is not the right tool to manipulate a given list. To do your task you should take a foreach loop like

foreach(var item in objects)
{
    item.v1 += obj.dv1;
}

What you can do is pre-select, which elements from objects you want by something like this

foreach(var item in object.Where(o => o.v1 % 2 == 0))

Like others mentioned you could self implement a ForEach() extension method, but there is a reason why it doesn't exist:
Take a look at Erics Blog entry.

查看更多
登录 后发表回答