开发者

Aggregate methods to use with IEnumerable lists

开发者 https://www.devze.com 2023-02-23 05:52 出处:网络
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?

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开发者_Python百科.Add(item);
}

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


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));


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.


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


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消