1

I have a linq to sql which creates a list of object

List<Student> Student= playerpoints.AsEnumerable()
                      .GroupBy(r => new { Name = r.Field<string>("ID"), Action = r.Field<string>("Name") })
                      .Select(grp => new Student
                      {

                          AwardName = grp.Key.Action,
                          Count = grp.Count()

                      }).ToList();

and i am converting it into list of objects using snippet in this method

Student[] objects = list.ConvertAll<Student>(item => (Student)item).ToArray();

Is there a way i can directly do this?

I mean instead of converting to list and then to a object array can i directly populate the array of objects instead of the list of object??

2
  • Can't you assign directly instead of assigning to a list in the first statement? Commented Jul 17, 2014 at 5:00
  • In 12 years as a c# developer I have never used ConvertAll I think it is not exactly deprecated but there is really no reason to ever use it either. Commented Jul 17, 2014 at 5:08

3 Answers 3

2

Yes. You can call ToArray() instead of ToList(). In order to become an array the query will execute exactly the same.

I should note that for many cases ToList can be slightly more preformant, and in a very few cases significantly more preformant.

You are likely returning this from a method though, in this method signature I strongly encourage the return value to be IEnumerable<Student> or ImmutableList<Student> (in the latter case you call .ToImmutableList()). Returning a List, an IList, or even to a lesser extent an array implies that you expect users to modify that collection, whereas the two I recommend do not. So long as your query has evaluated before you return there are no negatives to doing it this way.

Sign up to request clarification or add additional context in comments.

Comments

1

Call ToArray instead of ToList

Student[] objects = playerpoints.AsEnumerable()
                      .GroupBy(r => new { Name = r.Field<string>("ID"), Action = r.Field<string>("Name") })
                      .Select(grp => new Student
                      {

                          AwardName = grp.Key.Action,
                          Count = grp.Count()

                      }).ToArray();

Comments

1

directly you can return array

string[] Student= playerpoints.AsEnumerable()
                  .GroupBy(r => new { Name = r.Field<string>("ID"), Action = r.Field<string>("Name") })
                  .Select(grp => new Student
                  {

                      AwardName = grp.Key.Action,
                      Count = grp.Count()

                  }).ToArray();

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.