Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ select all items of all subcollections that contain a string

Tags:

c#

linq

I'm using jqueryui autocomplete to assist user in an item selection. I'm having trouble selecting the correct items from the objects' subcollections.
Object structure (simplified) is

public class TargetType
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<SubCategory> SubCategories { get; set; }

    public TargetType()
    {
        SubCategories = new HashSet<SubCategory>();
    }
}

public class SubCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<SubTargetType> SubTargetTypes { get; set; }

    public SubCategory()
    {
        SubTargetTypes = new HashSet<SubTargetType>();
    }
}

Currently I'm doing this with nested foreach loops, but is there a better way?
Current code:

List<SubTargetResponse> result = new List<SubTargetResponse>();
foreach (SubCategory sc in myTargetType.SubCategories)
{
    foreach (SubTargetType stt in sc.SubTargetTypes)
    {
        if (stt.Name.ToLower().Contains(type.ToLower()))
        {
            result.Add(new SubTargetResponse {
                Id = stt.Id,
                CategoryId = sc.Id,
                Name = stt.Name });
        }
    }
}
like image 938
Sami Avatar asked Nov 07 '15 10:11

Sami


1 Answers

You can do using Linq like this

var result = myTargetType.SubCategories
                         .SelectMany(sc => sc.SubTargetTypes)
                         .Where(stt => stt.Name.ToLower().Contains(type.ToLower()))
                         .Select(stt => new SubTargetResponse {
                                        Id = stt.Id,
                                        CategoryId = sc.Id,
                                        Name = stt.Name });

The above query doesn't work. The following should work, but I'd not recommend that as that'd not be faster or more readable.

var result = myTargetType.SubCategories
                         .Select(sc => new Tuple<int, IEnumerable<SubTargetType>>
                                            (sc.Id, 
                                             sc.SubTargetTypes.Where(stt => stt.Name.ToLower().Contains(type.ToLower()))))
                         .SelectMany(tpl => tpl.Item2.Select(stt => new SubTargetResponse {
                                        Id = stt.Id,
                                        CategoryId = tpl.Item1,
                                        Name = stt.Name }));
like image 189
Arghya C Avatar answered Nov 12 '22 14:11

Arghya C