C# – Using Linq to run a method on a collection of objects

clinq

This is a long shot, I know…

Let's say I have a collection

List<MyClass> objects;

and I want to run the same method on every object in the collection, with or without a return value. Before Linq I would have said:

List<ReturnType> results = new List<ReturnType>();
List<int> FormulaResults = new List<int>();
foreach (MyClass obj in objects) {
  results.Add(obj.MyMethod());
  FormulaResults.Add(ApplyFormula(obj));
}

I would love to be able to do something like this:

List<ReturnType> results = new List<ReturnType>();
results.AddRange(objects.Execute(obj => obj.MyMethod())); 
// obviously .Execute() above is fictitious
List<int> FormulaResults = new List<int>();
FormulaResults.AddRange(objects.Execute(obj => ApplyFormula(obj)));

I haven't found anything that will do this. Is there such a thing?

If there's nothing generic like I've posited above, at least maybe there's a way of doing it for the purposes I'm working on now: I have a collection of one object that has a wrapper class:

class WrapperClass {
  private WrappedClass wrapped;
  public WrapperClass(WrappedClass wc) {
    this.wrapped = wc;
  }
}

My code has a collection List<WrappedClass> objects and I want to convert that to a List<WrapperClass>. Is there some clever Linq way of doing this, without doing the tedious

List<WrapperClass> result = new List<WrapperClass>();
foreach (WrappedClass obj in objects)
  results.Add(new WrapperClass(obj));

Thanks…

Best Answer

Would:

results.AddRange(objects.Select(obj => ApplyFormula(obj)));

do?

or (simpler)

var results = objects.Select(obj => ApplyFormula(obj)).ToList();