Apply function to all elements of collection through LINQ [duplicate]

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

This question already has an answer here:

I have recently started off with LINQ and its amazing. I was wondering if LINQ would allow me to apply a function - any function - to all the elements of a collection, without using foreach. Something like python lambda functions.

For example if I have a int list, Can I add a constant to every element using LINQ

If i have a DB table, can i set a field for all records using LINQ.

I am using C#

回答1:

A common way to approach this is to add your own ForEach generic method on IEnumerable. Here's the one we've got in MoreLINQ:

public static void ForEach(this IEnumerable source, Action action) {     source.ThrowIfNull("source");     action.ThrowIfNull("action");     foreach (T element in source)     {         action(element);     } }

(Where ThrowIfNull is an extension method on any reference type, which does the obvious thing.)

It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.

Once you've got that, you can write things like:

people.Where(person => person.Age  person.EjectFromBar());


回答2:

The idiomatic way to do this with LINQ is to process the collection and return a new collection mapped in the fashion you want. For example, to add a constant to every element, you'd want something like

var newNumbers = oldNumbers.Select(i => i + 8);

Doing this in a functional way instead of mutating the state of your existing collection frequently helps you separate distinct operations in a way that's both easier to read and easier for the compiler to reason about.

If you're in a situation where you actually want to apply an action to every element of a collection (an action with side effects that are unrelated to the actual contents of the collection) that's not really what LINQ is best suited for, although you could fake it with Select (or write your own IEnumerable extension method, as many people have.) It's probably best to stick with a foreach loop in that case.



回答3:

You could also consider going parallel, especially if you don't care about the sequence and more about getting something done for each item:

SomeIEnumerable.AsParallel().ForAll( Action / Delegate / Lambda )

For example:

var numbers = new[] { 1, 2, 3, 4, 5 }; numbers.AsParallel().ForAll( Console.WriteLine );

HTH.



回答4:

haha, man, I just asked this question a few hours ago (kind of)...try this:

example:

someIntList.ForEach(i=>i+5);

ForEach() is one of the built in .NET methods

This will modify the list, as opposed to returning a new one.



回答5:

Or you can hack it up.

Items.All(p => { p.IsAwesome = true; return true; });


回答6:

For collections that do not support ForEach you can use static ForEach method in Parallel class:

var options = new ParallelOptions() { MaxDegreeOfParallelism = 1 }; Parallel.ForEach(_your_collection_, options, x => x._Your_Method_());


回答7:

You can try something like

var foo = (from fooItems in context.footable select fooItems.fooID + 1);

Returns a list of id's +1, you can do the same with using a function to whatever you have in the select clause.

Update: As suggested from Jon Skeet this is a better version of the snippet of code I just posted:

var foo = context.footable.Select(foo => foo.fooID + 1);


回答8:

I found some way to perform in on dictionary contain my custom class methods

foreach (var item in this.Values.Where(p => p.IsActive == false))             item.Refresh();

Where 'this' derived from : Dictionary

class MyCustomClass  {    public void Refresh(){} }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!