mihaifm / linq

linq.js - LINQ for JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Find Function

raiken-mf opened this issue · 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);

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

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);

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