Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find Function #70

Open
raiken-mf opened this issue Oct 30, 2019 · 3 comments
Open

Find Function #70

raiken-mf opened this issue Oct 30, 2019 · 3 comments

Comments

@raiken-mf
Copy link

	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
Copy link
Author

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

@mihaifm
Copy link
Owner

mihaifm commented Oct 30, 2019

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

@juancri
Copy link

juancri commented Jan 18, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants