Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select property of an object that is in a list of objects which is also in another list of objects

Tags:

c#

linq

I have the next arhitecture:

public class Element
{
    public uint Id { get; set; }
    public ICollection<ElementDetails> elementDetails { get; set; }
}
public class ElementDetails
{
    public string ElementTitle { get; set; }
    public string Content { get; set; }
}

And there's List<Element> someList that contains hundreds of elements. I'm trying to obtain a list of ElementTitle (strings) that contains a certain text (I've called it "seed"). What I want to accomplish it's a typeahead. Here is my attempt:

List<Element> suggestedElements = someList.Where(s => s.elementDetails.Any(ss => ss.ElementTitle.Contains(seed))).ToList();
List<string> suggestions = suggestedElements .SelectMany(t => t.elementDetails.Select(x => x.ElementTitle)).ToList() }); // contains all ElementTitle, including those ElementTitle that don't contain the "seed"...

How can I get rid of those elements that don't contain the seed?

like image 899
VladN Avatar asked May 09 '13 11:05

VladN


1 Answers

List<string> suggestions = someList.SelectMany(x => x.elementDetails)
                                   .Where(y => y.ElementTitle.Contains(seed))
                                   .Select(z => z.ElementTitle)
                                   .ToList();

Even simpler:

List<string> suggestions  = someList.SelectMany(x => x.elementDetails)
                                    .Select(y => y.ElementTitle);
                                    .Where(z => z.Contains(seed))
                                    .ToList();
like image 162
cuongle Avatar answered Sep 21 '22 18:09

cuongle