0

I'm having a difficulty returning a generic collection from a Linq Extension. I call the method with a single parameter:


   static List<NewPeople> GetPeople()
           {
               List<People> ppl = Enttity.GetCollection();
               var abc = new List<NewPeople>();
               ppl.CopyAllTo(abc);

               return abc;
               //return nppl;
           }

Called Method:



   public static IList<U> CopyAllTo<T, U>(this IEnumerable<T> source, List<U> destination) 
                   where T : class 
                   where U : class
           {
               List<U> objectList = new List<U>();
               foreach (T t in source)
               {
                   U u = Activator.CreateInstance<U>();
                   t.CopyTo(u);
                   objectList.Add(u);
               }

               return objectList;
           }

I can't get the list to return. When I break code on "return ObjectList", there are 3 objects in the list, however, on return to the caller, a null value is returned.

Does anyone know what's wrong with this picture?

3
  • Hint: You're not using destination, and you're not saving the return value from CopyAllTo. Commented May 19, 2020 at 6:07
  • I added a line before the return statement: destination = objectList, following that with return of destination. Not sure if you meant something like this or not by "Saving". I mean the objectList does have the items I'm looking for, but in return, there's nothing there. Commented May 19, 2020 at 6:17
  • 1
    See SomeBody's answer. Commented May 19, 2020 at 6:21

1 Answer 1

2

Either you'll have to assign the value to abc in your GetPeople method (remove the destination argument in your CopyAllTo method):

static List<NewPeople> GetPeople()
{
    List<People> ppl = Enttity.GetCollection();
    List<NewPeople> abc = ppl.CopyAllTo<People,NewPeople>();

    return abc;
    //return nppl;
}

Or you use the destination variable in your CopyAllTo method (this is possible because List<T> is a reference type):

public static void CopyAllTo<T, U>(this IEnumerable<T> source, List<U> destination) 
    where T : class 
    where U : class
{
    foreach (T t in source)
    {
        U u = Activator.CreateInstance<U>();
        t.CopyTo(u);
        destination.Add(u);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.