Devin Burke
Devin Burke

Reputation: 13820

Aggregate methods to use with IEnumerable lists

Is there a way to "convert" (return) an IEnumerable list of, e.g., strings to an IEnumerable list of a different type when that different type accepts the former type in its constructor?

For example, the DataTable.Columns.AddRange() method accepts only lists of columns. Is there a way to return a DataColumn list by offering a string list using LINQ or some sort of aggregate function? I imagine the code would roughly do the following, but in one line:

var columnList = new List<DataColumn>();
foreach (var item in myStringList)
{
    columnList.Add(item);
}
return columnList;

Likewise, is there an aggregate method that will take a list and run each of its members against a specific method? For example, I am looking for a one line way to perform the following similar foreach loop:

foreach (var item in myStringList)
{
    myDataTable.Columns.Add(item);
}

Obviously, I am looking for generic answers that are not actually dependent on data columns or strings.

Upvotes: 1

Views: 3154

Answers (4)

Amy B
Amy B

Reputation: 110071

Call Enumerable.Aggregate

List<DataColumn> result = myStringList.Aggregate(
  new List<DataColumn>(),
  (list, item) => { list.Add(item); return list; }
);

return result;

That said, foreach statement is better.

Upvotes: 2

Alessandro
Alessandro

Reputation: 3761

myStringList.ForEach(item => myDataTable.Columns.Add(item));

EDIT: that's not Linq. Sorry, my mistake.

Upvotes: 0

Tejs
Tejs

Reputation: 41236

Yes, in fact, although not all of them are LINQ specific. ForEach is just a List method. For your two examples:

myStringList.ForEach(x => columnList.Add(x));
// assumes myStringList is a List<T>... otherwise convert your enumerable using ToList()

The ForEach method takes an Action and lets you perform some logic on each item. So if you want to do transformations, it's easy enough combining with select:

myStringList.Select(x => new DataColumn(x))
      .ToList()
      .ForEach(x => columnList.Add(x));
// transforms each element of the string by adding some text, then calling foreach 
// on the items

Upvotes: 1

SLaks
SLaks

Reputation: 887225

You can write

var newList = list.ConvertAll(x => new Something(x));
list.ForEach(x => DoSomething(x));

These methods are defined by th List<T> class.

If you have an arbitrary IEnumerable<T>, you can use LINQ:

var newEnumerable = enumerable.Select(x => new Something(x));

Upvotes: 3

Related Questions