0

I have a basic array list of objects. It accepts a string, a double, a double and a string. I need to sort the list by the final string. How do I sort this array list by typeIn which is a string?

private void button1_Click(object sender, EventArgs e)
        {
            nameIn = textBox1.Text;
            lengthIn = Double.Parse(textBox2.Text);
            weightIn = Double.Parse(textBox3.Text);
            typeIn = textBox4.Text;

            Bird newBird = new Bird(nameIn, lengthIn, weightIn, typeIn);

            birdList.Add(newBird);

         var sortedList = Bird.birdlist.OrderBy(x => x.Type).ToList();

        }

It does not allow me to order by. The red underline in the error is under Orderby

dusk42
  • 21
  • 4
  • Possible duplicate of [How to Sort a List by a property in the object](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – Broots Waymb May 06 '19 at 16:51
  • There's a little uncertainty from the terms you're using. Sorting and grouping are two different things. – Scott Hannen May 06 '19 at 16:51
  • When you say a "basic array list of objects" what do you mean? `ArrayList` or a `List`, or a `List`?? – Rufus L May 06 '19 at 17:24
  • Are you sure that the `birdList.Add()` is the same list as `Bird.birdlist.OrderBy()`? is it a static field of the class Bird? – Jeroen van Langen May 06 '19 at 18:55

1 Answers1

2

You can try OrderBy() Linq. OrderBy sorts elements in ascending order.

var sortedList = birdList.OrderBy(x => x.TypeIn).ToList();

Here I considered TypeIn is a property with string as a datatype

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • I have tried but I keep getting the error: CS1061. My array list is in the class that has the constructor and when I try your solution, it red underlines orderby – dusk42 May 06 '19 at 17:27
  • What error you are facing.. please update your question with error and what you tried so far – Prasad Telkikar May 06 '19 at 17:32
  • why `Bird.birdlist`? is it static..? what is error please mention error? red line indicates compile time error – Prasad Telkikar May 06 '19 at 17:37
  • Yes, I have declared the birdlist in the Bird class as public static ArrayList birdlist = new ArrayList();. The error: 'ArrayList' does not contain a definition for 'OrderBy' and no accessible extension method 'OrderBy' accepting a first argument of type 'ArrayList' could be found (are you missing a using directive or an assembly reference?) – dusk42 May 06 '19 at 17:42
  • Have you put "using System.Linq" at the top of your file? – dazedandconfused May 08 '19 at 20:00
  • @dazedandconfused Yes, `OrderBy()` and `.ToList()` both are present in System.Linq. we need to import this library into our solution, otherwise it gives compile time error. To answer your question I added `using System.Linq` at the top of my file – Prasad Telkikar May 09 '19 at 04:53