Reputation: 2313
I have following code snippet to fetch data as IEnumarable list and filter them using LINQ and insert those details to List/
IEnumerable<User> listUsers = ..// From DB
List<User> filteredUsers = new List<User>();
if (listUsers != null)
{
foreach(var user in listUsers)
{
filteredUsers = listUsers.Where(x => x.GroupID == item).ToList();
}
}
How to insert these Each filteredUsers
item to collection , I tried something like below but this is with compile time errors, how to do this properly
IEnumerable<User> listUsers = ..// From DB
List<User> filteredUsers = new List<User>();
IEnumerable<User> salistUsers = new List<User>();
if (listUsers != null)
{
foreach(var user in listUsers)
{
filteredUsers = listUsers.Where(x => x.GroupID == item).ToList();
salistUsers.Add(filteredUsers);
}
}
Upvotes: 0
Views: 170
Reputation: 3002
You can't use .Add
with an IEnumerable
, salistUsers sould be a List
:
List<User> salistUsers = new List<User>();
The Add
method is used to add a single object.
Try AddRange
instead, which allows you to add a list:
if (listUsers != null && !listUser.Any())
{
var filteredUsers = listUsers.Where(x => x.GroupID == item).ToList();
salistUsers.AddRange(filteredUsers);
}
Upvotes: 0
Reputation: 11544
Change salistUsers
type from IEnumerable<User>
to List<Users>
and use List.AddRange(collection As IEnumerable(Of T)) method.
IEnumerable<User> listUsers = ..// From DB
List<User> salistUsers = new List<User>();
if (listUsers != null && !listUser.Any())
{
var filteredUsers = listUsers.Where(x => x.GroupID == item).ToList();
salistUsers.Add(filteredUsers);
}
Upvotes: 1