linq icon indicating copy to clipboard operation
linq copied to clipboard

Find Function

Open raiken-mf opened this issue 4 years ago • 3 comments

	Enumerable.prototype.find = function (compareSelector) {
        compareSelector = Utils.createLambda(compareSelector);
		
		var result = null;
		
		this.forEach(function(item) {
			if (compareSelector(item)) {
				result = item;
				return;
			}
		});
		
		return result;
    };

Usage:

var result = Enumerable.from(list).find("x => x.Id == " + somevariable.Id);

It works fine and I hope you like it. It could use some optimization of code quality though. I don't like the "x => x.Id == " + somevariable.Id part, because the somevariable.Id is outside of the quotation marks. Maybe you got a better solution for this problem.

C# Equivalent would be:

        public static T Find<T>(this IList<T> source, Func<T, bool> condition)
        {
            foreach (var item in source)
            {
                if (condition(item))
                {
                    return item;
                }
            }
            return default(T);
        }

Usage:

var result = list.Find(x => x.Id == somevariable.Id);

raiken-mf avatar Oct 30 '19 08:10 raiken-mf

Just figured out... this function is from the System.Collections.Generic.List class... not from Linq..

raiken-mf avatar Oct 30 '19 08:10 raiken-mf

Maybe you got a better solution for this problem.

Try not to use lambdas constructed from strings, that part of the library is a bit obsolete.

var result = Enumerable.from(list).find(x => x.Id == somevariable.Id);

mihaifm avatar Oct 30 '19 22:10 mihaifm

is this the same as firstOrDefault(...)?

juancri avatar Jan 18 '21 08:01 juancri