How to add the IEnumerable collection to ICollection list?

1.8k views Asked by At

I add the method for adding Ienumerable collection to Icollection.

public static ICollection<T> AddTo<T>(this IEnumerable<T> list,ICollection<T> collection) {
    foreach (T item in list) {
        collection.Add(item);
    }
    return collection;
}

But at first time initialized collection variable as null.Then i am getting "Object reference not found error"please tell me how to add Ienumerable list data to Icollection properly?

EDIT:

 ICollection<UserInApplication> userInAppRole=null;
                IEnumerable<UserInApplication> result=null;
   result = _userService.UserInApplicationRoles(iAppRoleId,  collection["displayName"]).AsEnumerable();
     userInAppRole = Extensions.AddTo<UserInApplicationRole>(result,userInAppRole);
3

There are 3 answers

0
Mat J On BEST ANSWER

You are not initializing your collection. And extension methods can be called in a better way.

ICollection<UserInApplication> userInAppRole=new Collection<UserInApplication>(); //Initialize this
IEnumerable<UserInApplication> result=null;
result = _userService.UserInApplicationRoles(iAppRoleId,collection["displayName"])
                     .AsEnumerable();
 userInAppRole = result.AddTo(userInAppRole); 
0
Daniel Mann On

Look at this code:

ICollection<UserInApplication> userInAppRole=null;
IEnumerable<UserInApplication> result=null;
result = _userService.UserInApplicationRoles(iAppRoleId,  collection["displayName"]).AsEnumerable();
userInAppRole = Extensions.AddTo<UserInApplicationRole>(result,userInAppRole)

You're never instantiating a collection in the userInAppRole variable; it's null. When you try to add result into a null, you get an exception.

0
Sam Axe On
public static ICollection<T> AddTo<T>(this IEnumerable<T> list,ICollection<T> collection) {
  if ((null != list) || (null != collection)) {    
    foreach (T item in list) {
        collection.Add(item);
    }
  }
    return collection;
}