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??

Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150
  • Can't you assign directly instead of assigning to a list in the first statement? – shree.pat18 Jul 17 '14 at 05: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. – George Mauer Jul 17 '14 at 05:08

3 Answers3

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.

Community
  • 1
  • 1
George Mauer
  • 117,483
  • 131
  • 382
  • 612
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();
Adil
  • 146,340
  • 25
  • 209
  • 204
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();
biswapm
  • 31
  • 4