Thomas Adrian
Thomas Adrian

Reputation: 3636

Sorting collection using OrderBy not working

I am trying to sort my collection using lambda according to (in this case "Amount") but also tried other fields. when I output the collection using foreach it is not sorted according to the field

Accounts? ac = await Client.SendRequest<Accounts>(tk.access_token, Method.GET, "/UploadedAccounts", "");
                ac.value.OrderBy(x => x.Amount);
                ac.value.RemoveAll(x => x.Year.ToString() != YearBox.Text);

 foreach (var a in ac.value) {
                    ListViewBox.Items.Add(a.CompanyLegalName + " / " + a.Year + "-" + a.Month + " / " + a.AccountName + " / " + a.AccountCode + " / " + a.AccountType + " / " + a.Amount + " / " + a.Dimension , 0);
                }

I have also tried to do the sorting after the 'RemoveAll' what am I doing wrong?

Upvotes: 1

Views: 223

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

.OrderBy(x => x.Amount) sorts the collection and returns sorted Accounts. You need to do foreach on the list which is return by .OrderBy(x => x.Amount)

Like,

foreach (var a in ac.value.OrderBy(x => x.Amount)) 
{
     ListViewBox.Items.Add(a.CompanyLegalName + " / " + a.Year + "-" + a.Month + " / " + a.AccountName + " / " + a.AccountCode + " / " + a.AccountType + " / " + a.Amount + " / " + a.Dimension , 0);
}

Upvotes: 3

Volodymyr
Volodymyr

Reputation: 287

The issue is that OrderBy LINQ extension is returning sorted enumerable. It is not modifying the original collection.

Upvotes: 1

Related Questions