Ben Hoffman
Ben Hoffman

Reputation: 8259

Sorting IEnumerable<int> in IEnumerable<IEnumerable<int>>

I have an object of type IEnumerable<IEnumerable<int>>. I need to sort the ints within the inner IEnumerable<int> but I am not sure how to do this.

I attempted to convert IEnumerable<IEnumerable<int>> to List<List<int>> to make the sort easier with this code:

var sortedResults = results.ForEach(x => x.ToList());

But I receive the error "Cannot assign void to implicitly-typed variable"

I also receive the same error if I to the sorting and the conversion all at once:

var sortedResults = results.ToList().ForEach(x => x.ToList().Sort((a ,b) => a.CompareTo(b))));

What is the best way to do this?

Upvotes: 1

Views: 6137

Answers (3)

WizardDBA
WizardDBA

Reputation: 46

I tried to draw an example of how to order using IEnumerable I think I can help you understand how it works. Observe the example, I hope have helped to you understand Example:

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        class Person
        {
            public string name { get; set; }
            public int personage { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Person[] p ={new Person{name="Alice",personage=10 },
                         new Person{name="Alex",personage=11},
                         new Person{name="Danny",personage=12}};
            IEnumerable<Person> query = p.OrderBy(ps => ps.personage);
            foreach (Person item in query)
            {
                textBox1.Text += item.name + item.personage.ToString() + Environment.NewLine;
            }

        }

Result of this is:
Alice10
Alex11
Danny12

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838156

var sortedResults = results.Select(list => list.OrderBy(x => x));

Upvotes: 3

BrokenGlass
BrokenGlass

Reputation: 160882

Just use OrderBy - since these are integers that means you can use the number itself as criteria:

sortedResults = results.Select(x => x.OrderBy(num => num));

Above assumes you want the output to be just a IEnumerable<IEnumerable<int>> if you need lists, use ToList() were needed.

Upvotes: 8

Related Questions