开发者

What is the eqivalent to a SQL "in" clause here?

I'm new to LINQ and I've been at this for hours now. I have a List<> of objects where one of the objects properties is a List of selected categories. I also have, outside of the objects, a List representing a subset of categories and I want to return all objects which contain at least one category that is also in the subset as illustrated in the following pseudo code (not my actual code)

List<string> subset = cat, dog, mouse

List<myclass> myclasses = 
   {name:alphie, category:[cat,elephant]},{name:sally, category:[fish]}, {name:bob, category:[dog, mouse]}

In the above example I need to return alphie and bob since they both have at least one category that's in my subset.

The only solution so far is to get a list of both and then use expensive foreach loops to go through and compare. I'm sure LINQ must provide a more efficient way to achieve the same?

More details (I think my pseudo code is not detailed enough)

public class RadioProgram {
   ...
   private List<string> _category = new List<string>();
   public List<string> Category { get { return _category; } set { _category = value; }         }
   ...
}

public class Category {
   ...
   private string _categoryName = "";
   private List<Category> _subCategories = new List<Category>();
   public string CategoryName { get { return _categoryName; } set { _categoryName = value; } }
   public List<Category> SubCategories { get { return _subCategories; } set { _subCategories = value; } }
   ...
}

I have a method, GetCategories(string parentCategory), that returns all child categoryNames as List. Each radioProgram.Category (yes, name needs to be ref开发者_StackOverflowactored to plural) is itself a List and may contain zero, one or more categoryNames. I'm getting my master list of radioPrograms and I want to return a subset that contain where each one contains at least one categoryName that matches the set from GetCategories.

I'm trying to avoid changing the architecture of the application (which is a potential solution) as it means a lot of refactoring of existing functionality AND I think this happens to be a good exercise for tackling and understanding LINQ.


One thing you could use is

myclasses
    .Where(o => o.category.Any(c => subset.Contains(c)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜