0

I have the following class

public class Group
{
    public string Id { get; set; }
    public string Name { get; set; }
}

and 2 lists List<string> groupRestrict and List<Group> groups

now the group list contains some groups with all fields filled in and I want to select all the restricted groups, the groupRestrict list contains just the name of the groups.

I tried some things, but for some reasons, it always returns an empty list. this as my last test:

var lst = groups.Where(j => groupRestrict.Contains(j.Name)).ToList();

Any clue what might be going wrong?

Edit: Like the comments said, this should have worked, it was the input that had some ' but now I would like to have that the groupRestrict doesn't have to be the exact name, but can use 'like' features.

current expression:

var restrictedGroups = (from gr in groupRestrict join g in groups on gr equals g.Name select g).ToList();

12
  • 2
    Be aware that this is a bigO - rather do this query on a HashSet (or Dictionary) and think about using .Join or .GroupJoin (whether you want a left or full join) Commented Feb 23, 2015 at 13:01
  • @AndreasNiedermair it's not on a SQL database, if that is what you are refering to :) Commented Feb 23, 2015 at 13:02
  • 5
    This should work. Be aware that string comparison is case sensitive by default. Commented Feb 23, 2015 at 13:03
  • Kiwi, no. @AndreasNiedermair means Join function in LINQ. Commented Feb 23, 2015 at 13:03
  • 2
    Sounds like it should work (albeit relatively inefficiently if groupRestrict is large) - please show a short but complete program demonstrating the problem. Commented Feb 23, 2015 at 13:04

1 Answer 1

2

Try:

var lst = groups.Where(j => groupRestrict.Any(x=> j.Name.Contains(x))).ToList();

this would match all groups with names that contain one or more strings from the searchList.

Case insensitive variant would be:

var lst = groups.Where(j => groupRestrict.Any(x=> j.Name.ToLower().Contains(x.ToLower()))).ToList();

Allthough it would be better to convert the groupRestrict to lowercase prior to the query in this case and you can omit the .ToLower() call for x:

string[] lowerCaseGroupRestrict = groupRestrict.Select(x=> x.ToLower()).ToArray();
var lst = groups.Where(j => lowerCaseGroupRestrict.Any(x=> j.Name.ToLower().Contains(x))).ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

Nice thanks! The groupRestrict is a user input (although it's get checked and filtered first) . so the prior can be easy called :)
Sorry, totally forgot it! :)

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.