foreach ( var element in collection)
{
// Do something
}
* This source code was highlighted with Source Code Highlighter .
Therefore, such a wrapper was formed. public static IEnumerable <T> Each<T>( this IEnumerable <T> list, Action<T> func)
{
if (func == null )
{
return list;
}
if (list == null )
{
return null ;
}
foreach ( var elem in list)
{
func(elem);
}
return list;
}
* This source code was highlighted with Source Code Highlighter .
When checking the arguments, it would be more convenient to write throw new ArgumentNullException, but for my tasks it is better to use the “failed, well and good” mechanism.public static IEnumerable <T> Each<T>( this IEnumerable <T> list, Action<T, int > func)
{
if (func == null )
{
return list;
}
if (list == null )
{
return null ;
}
int i = 0;
foreach ( var elem in list)
{
func(elem, i);
i++;
}
return list;
}
* This source code was highlighted with Source Code Highlighter .
Now, replacing various odds has become a bit more convenient. The code has become more beautiful.// .
ddSelector.Items. Cast <ListItem>().Each((x, i) => x.Text = (i+1) + ": " + x.Text);
//
radioButtonList1.Items. Cast <ListItem>().Each(x => x.Selected = true );
// , - Add AddRange.
listToAdd.Each(someObject.Add);
// object.Add , .
* This source code was highlighted with Source Code Highlighter .
From a certain moment on, I ran into another problem.public static IEnumerable <T> EachLazy<T>( this IEnumerable <T> list, Action<T> func)
{
foreach ( var elem in list)
{
func(elem);
yield return elem;
}
}
* This source code was highlighted with Source Code Highlighter .
Thanks to the yield return construct, we get that the action will be executed only when we really need the values.Source: https://habr.com/ru/post/51620/
All Articles