3

I've got an list where myclass is defined with a few properties

List<MyClass> myClassList = new List<MyClass>();
myClassList.Add(new MyClass() { Id = 1, Name = "My first test", Key = "First" });
myClassList.Add(new MyClass() { Id = 2, Name = "My second test", Key = "Second" });

I then have a path i.e. c:\my folders\company name\My First Test, which I break into a string array using regex i.e. myArrayPath

I want to find if any elements of myClassList based on a given property i.e. Name can be found in any of the elements from myArrayPath and ideally I'd like to return the Key but if I return the object matching one of the element from myArrayPath, this will be just as good.

Is there a way to achieve this using linq and/or lambda expressions.

Thanks.

1 Answer 1

11

This can be quite easily done with LINQ:

var keyResult = myClassList.Where(x=>myArrayPath.Contains(x.Name))
    .Select(x=>x.Key);

if you need it in the form of a list of an array, just add .ToList() or .ToArray() at the end of it.

Sign up to request clarification or add additional context in comments.

1 Comment

Spot on!! I've just changed the above code slightly to return the actual key as all values in both arrays will be unique, so no need for a list to be returned. string key = myClassList.Where(x=>myArrayPath.Contains(x.Name)) .Select(x=>x.Key).First();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.