Alex
Alex

Reputation: 233

Anonymous types add to a list

I have a list and there's some anonymous types.In here i'm unable to get a return and also return here is 0.

public IList<Supervisors> GetSupervisors()
    {
        List<Supervisors> lst = new List<Supervisors>();

        var AllUsr = iuserrepository.GetList(x => x.UserId != null);
        var xRole = irolerepository.GetSingle(x => x.RoleName.Equals("Supervisor"));
        var yRole = iusersinrolerepository.GetList(x => x.RoleId.Equals(xRole.RoleId));
        var userIds = yRole.Select(s=>s.aspnet_Users.UserId).ToList();
        var supRole = iuserrepository.GetList(x => x.UserId != null && userIds.Contains(x.UserId)).Select(x => new {UserId = x.UserId,UserName = x.UserName }).ToList();



        return lst;//<-- in here lst return 0.How to add it to a list
    }

Upvotes: 1

Views: 1009

Answers (3)

Christos
Christos

Reputation: 53958

Initially you create an empty list:

List<Supervisors> lst = new List<Supervisors>();

and then in your method's body, you don't add any items in it.

Hence, when you return it the list is empty.

Furthermore, you can add only objects in this list, whose type is Supervisors. You can't add an anonymous type object.

From that you have posted, I would suggest something like the following:

var supRole = iuserrepository.GetList(x => x.UserId != null && 
                                      userIds.Contains(x.UserId))
                             .Select(x => new Supervisors
                              {
                                  UserId = x.UserId,
                                 UserName = x.UserName 
                              });

Then add the above sequence to your list:

lst.AddRange(supRole);

What we have done above, is to make a projection of each element in the sequence that is returned from the GetList to an object of type Supervisors. As a result, the type of supRole would be IEnumerable<Supervisors>. So, we can use later the list's AddRange method to add these objects to the list.

Important Note

Since I am not aware of the Supervisors class definition, I might be wrong using the property names UserId and UserName . If that's the case, you should correct it correspondingly.

Upvotes: 3

VinothNair
VinothNair

Reputation: 634

you can use [SourceList].AddRange([TargetList]); Please check the below link http://www.dotnetperls.com/list-addrange

Upvotes: 0

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3182

you didn't add the values to the list thats why it return 0

List<int> _list= new List<int>();
        _list.Add(2);

more

Upvotes: 0

Related Questions