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?
(from a in myFax where a.Readers.Any(r => myGroups.Contains(r)) select a).ToList()db.vwFax.AsQueryable().Where(x=> myGroups.Any(y=> x.Contains(y)).ToList();you can also create a stored proc instead of LINQ.if(res.Count() > 0){outRes.AddRange(res);}because you are executing the SQL querymyGroups.Counttime, instead of executing one big query. Using LINQ queries above you will execute only one query.