Hello, today I release some custom System.Linq extensions which works better because it uses foreach except of while. For now it only works with arrays (like int[] and string[]), dictionary and list, and I've only created ForEach and While (using foreach loop, not while loop)
For using it, you need to remove this at the using System; block:
And add:PHP Code:using System.Linq;
Then add this class to your C# Project:PHP Code:using CustomLinqExtensions;
NOTE:PHP Code:using System;
using System.Collections.Generic;
namespace CustomLinqExtensions
{
public static class LinqExtensions
{
#region ForEach
public static void ForEach<T>(this List<T> items, Action<T> action)
{
foreach (var Item in items)
{
action.Invoke(Item);
}
}
public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> items, Action<TKey, TValue> action)
{
foreach (var Item in items)
{
action.Invoke(Item.Key, Item.Value);
}
}
public static void ForEach<T>(this T[] items, Action<T> action)
{
foreach (var Item in items)
{
action.Invoke(Item);
}
}
#endregion
#region While
public static List<T> While<T>(this List<T> items, Func<T, bool> expression)
{
List<T> Items = new List<T>();
foreach (var Item in items)
{
if (expression.Invoke(Item))
Items.Add(Item);
}
return Items;
}
public static Dictionary<TKey, TValue> While<TKey, TValue>(this Dictionary<TKey, TValue> items, Func<TKey, TValue, bool> expression)
{
Dictionary<TKey, TValue> Items = new Dictionary<TKey, TValue>();
foreach (var Item in items)
{
if (expression.Invoke(Item.Key, Item.Value))
Items.Add(Item.Key, Item.Value);
}
return Items;
}
public static T[] While<T>(this T[] items, Func<T, bool> expression)
{
List<T> Items = new List<T>();
foreach (var Item in items)
{
if (expression.Invoke(Item))
Items.Add(Item);
}
return Items.GetArray();
}
#endregion
#region GetArray
public static T[] GetArray<T>(this List<T> items)
{
T[] Array = new T[items.Count];
int pos = 0;
foreach (var item in items)
Array[pos++] = item;
return Array;
}
#endregion
}
}
With the List<int> etc you need to use ForEach<TYPE>(....) because List always uses the ForEach() method which is already implemented.
Another note, I'll explain something:
ForEach just replaces for example this:
While just replaces for example this:PHP Code:foreach (var i in new int[] { 1, 2, 3, 4, 5 })
{
Console.WriteLine(i);
}
GetArray just pushes every value of a LIST (only a list for now) into an array of the specified type.PHP Code:List<int> vals = new List<int>();
foreach (var i in new int[] { 1, 2, 3, 4, 5 })
{
if (i % 2)
vals.Add(i);
}
return vals;
For using you only have to use type argument if you use list, since list has implemented ForEach. If you still want to use ForEach with my method, you can create a new ForEach extension for IList which doesn't have implemented ForEach (I think)
Credits:
Me 95% - Creating code
MS 5% - Giving explaination



Reply With Quote![[C#] Better Linq Extensions](http://ragezone.com/hyper728.png)



