views:

42

answers:

3

Hi guys. I guess this is trivial but not for me.

I have a collection MembershipUserCollection. I wanted to perform some Linq query over it so I've used OfType<MembershipUser>() method and then applied Where() on it. However, I do not know how to cast back my results to MembershipUserCollection?

This is my code:

MembershipUserCollection Users;
Users = GetAllUsers(pageIndex, pageSize, out totalRecords).OfType<MembershipUser>().Where(user => user.Email == emailToMatch); //how to cast it back to MembershipUserCollection ?

GetAllUsers(pageIndex, pageSize, out totalRecords) is returning MembershipUserCollection

Thanks for your time.

+1  A: 

I don't think you can do it in the query itself, but you should be able to do this:

var query = GetAllUsers(pageIndex, pageSize, out totalRecords)
                .OfType<MembershipUser>()
                .Where(user => user.Email == emailToMatch);

var users = new MembershipUserCollection();
foreach (var user in query)
{
    users.Add(user);
}

(And, of course, you could wrap that logic up into an extension method if you wanted and then call the extension method in the query.)

LukeH
Thanks, Compiler says that there is an explict cast.
Wodzu
A: 

One of the possible solutions:

   var users = GetAllUsers(pageIndex, pageSize, out totalRecords)
      .OfType<MembershipUser>()
      .Where(user => user.Email == emailToMatch);

   MembershipUserCollection membershipUsers = new MembershipUserCollection();
   users
      .ToList()
      .ForEach(membershipUsers.Add);

Another one with foreach statement:

foreach (var user in users)
{
    membershipUsers.Add(user);
}
Restuta
A: 

So it was trivial, I just had to cast it like this:

MembershipUserCollection Users;
Users = (MembershipUserCollection)GetAllUsers(pageIndex, pageSize, out totalRecords).OfType<MembershipUser>().Where(user => user.Email == emailToMatch).Cast<MembershipUser>();

Thanks guys for your asnwers.

Wodzu
Unfortunately it doesn't work. VS IDE accepted this but during compilation it returned error.
Wodzu