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

4
  • Possible duplicate of How to Sort a List<T> by a property in the object Commented May 6, 2019 at 16:51
  • There's a little uncertainty from the terms you're using. Sorting and grouping are two different things. Commented May 6, 2019 at 16:51
  • When you say a "basic array list of objects" what do you mean? ArrayList or a List<object>, or a List<Bird>?? Commented May 6, 2019 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? Commented May 6, 2019 at 18:55

1 Answer 1

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

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

6 Comments

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
What error you are facing.. please update your question with error and what you tried so far
why Bird.birdlist? is it static..? what is error please mention error? red line indicates compile time error
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?)
Have you put "using System.Linq" at the top of your file?
|

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.