📜 ⬆️ ⬇️

Foreach wrapper

Recently, I was annoyed by the bulkiness of the code, hulking constructs and the presence of extra lines.
A simple foreach in accordance with the codestyle turns into at least 4 lines of text
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.

Further, as I use it, I ran into a problem when I needed to know the index of the item being processed. For this, I used the following extension:
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.
Example of use:
// .
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.
There is a long series of methods and Linq, then some kind of Each, then again Linq, then again Each, and then the whole collection is given to the devil knows where, and only the first 10 elements of this collection are used there.
It turns out that everything was calculated, executed, assigned, and the result is not needed by anyone. To overcome this nefariousness I had to fill the list with one more Each.
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.
Accordingly, it became possible to write constructions
return ArrayOfInstances.EachLazy (x => x.Parametr = defaultValue) .Select (x => x.SomeValue)
.EachLazy (x => x. Parent = null );

Here is such a man-made sugar.

')

Source: https://habr.com/ru/post/51620/


All Articles