1

I'm very new to LINQ and I'm searching to filter an SQL view which has a column called 'Readers' containing several group names separated by '#' (es. "Administrators#HR Group#Employees Group"). Having a list of user's groups, I need to extract all the records where Readers contains at least one of the user's groups. In other words, the user must see only those records belonging to him.

I found this solution, but I think it's extremely inefficient:

private List<vwFax>getmyFaxes(List<string> myGroups)
{
    var myFax = db.vwFax.AsQueryable();
    var res = db.vwFax.AsQueryable();
    List<vwFax> outRes= new List<vwFax>();

    foreach (string elem in myGroups)
    {
        res = (from a in myFax
                where a.Readers.Contains(elem)
                select a); 
        if(res.Count() > 0)
        {
            outRes.AddRange(res);
        }               
    }
    return outRes.ToList();
}

Any help please?

3
  • Maybe (from a in myFax where a.Readers.Any(r => myGroups.Contains(r)) select a).ToList() Commented Aug 3, 2016 at 11:04
  • db.vwFax.AsQueryable().Where(x=> myGroups.Any(y=> x.Contains(y)).ToList(); you can also create a stored proc instead of LINQ. Commented Aug 3, 2016 at 11:06
  • Looks like the problem is with if(res.Count() > 0){outRes.AddRange(res);} because you are executing the SQL query myGroups.Count time, instead of executing one big query. Using LINQ queries above you will execute only one query. Commented Aug 3, 2016 at 11:10

1 Answer 1

2

Basically what you are saying in the following query is: For each item in myFax take it only if that item.Readers contains Any (at least 1) of the items in myGroups

outRes = db.myFax.Where(item => myGroups.Any(grp => item.Readers.Contains(grp)));

and in query-syntax:

outRes = from item in db.myFax
         where myGroups.Any(grp => item.Readers.Contains(grp))
         select item;
Sign up to request clarification or add additional context in comments.

Comments

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.