Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

[C#] Better Linq Extensions

Custom Title Activated
Loyal Member
Joined
Oct 26, 2012
Messages
2,357
Reaction score
1,086
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:

PHP:
using System.Linq;

And add:

PHP:
using CustomLinqExtensions;

Then add this class to your C# Project:

PHP:
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
    }
}

NOTE:
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:

PHP:
foreach (var i in new int[] { 1, 2, 3, 4, 5 })
{
Console.WriteLine(i);
}

While just replaces for example this:

PHP:
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;

GetArray just pushes every value of a LIST (only a list for now) into an array of the specified type.

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
 
Joined
Aug 6, 2005
Messages
552
Reaction score
298
Hello, today I release some custom System.Linq extensions which works better because it uses foreach except of while.
And why is it better? I don't see the point :?:
Your extensions also are limited to specific types, while it's better to code against interfaces.

ForEach-Extensions:
I would just make one for IEnumerable<T>.

While-Extensions:
I don't get why you named them "While", when they don't stop when the expression returns false.
What you want to achieve with this code is already in System.Linq-Extensions, it would be .Where(...) or .TakeWhile(...)

GetArray-Extension:
Already implemented in System.Linq-Extensions, called ToArray(). There are also ToList() and ToDictionary(...)


Examples to replace your examples:
ForEach just replaces for example this:

PHP:
foreach (var i in new int[] { 1, 2, 3, 4, 5 })
{
Console.WriteLine(i);
}
Code:
Enumerable.Range(1, 5).ForEach(Console.WriteLine);
While just replaces for example this:

PHP:
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;
your example doesn't even compile ;) However if you want each value when the modulo returns 0 as list:
Code:
var values = Enumerable.Range(1, 5).Where(i => i % 2 == 0).ToList();

I recommend reading the 101 LINQ Samples in MSDN :thumbup1:
 
Last edited:
Custom Title Activated
Loyal Member
Joined
Oct 26, 2012
Messages
2,357
Reaction score
1,086
And why is it better? I don't see the point :?:
Your extensions also are limited to specific types, while it's better to code against interfaces.

ForEach-Extensions:
I would just make one for IEnumerable<T>.

While-Extensions:
I don't get why you named them "While", when they don't stop when the expression returns false.
What you want to achieve with this code is already in System.Linq-Extensions, it would be .Where(...) or .TakeWhile(...)

GetArray-Extension:
Already implemented in System.Linq-Extensions, called ToArray(). There are also ToList() and ToDictionary(...)


Examples to replace your examples:

Code:
Enumerable.Range(1, 5).ForEach(Console.WriteLine);

your example doesn't even compile ;) However if you want each value when the modulo returns 0 as list:
Code:
var values = Enumerable.Range(1, 5).Where(i => i % 2 == 0).ToList();

I recommend reading the 101 LINQ Samples in MSDN :thumbup1:

Microsoft's LINQ expressions use:

using .......
 
Elite Diviner
Joined
May 30, 2011
Messages
443
Reaction score
95
"using" doesn't have any overhead (after optimizations). using(var v) just instantiates v and then calls v.Dispose() when it falls out of the using scope. It doesn't look any different in IL than manually instantiating/disposing variables. You could say that Dispose() is slower, but that depends what you're iterating over and in general if you're stressing over a using versus a foreach block you're missing the point of LINQ. LINQ isn't supposed to be terribly fast, but it is supposed to be a quick way to query over objects. Your code doesn't even query, it just copies IEnumerables based on a Predicate<T>.
 
Joined
Aug 6, 2005
Messages
552
Reaction score
298
Using is slower than foreach.
Well, guess what your foreach-loop does in the background. It also creates an enumurator-object which gets disposed after your loop finished. Your code is creating additional overhead by creating new objects (lists, arrays), so how it's gonna be faster?
I would not want to sacrifice the elegant and powerful Linq-Extensions, in the most cases the difference to really optimized code does not even matter.
 
Back
Top