Home > other >  Sorting collection using OrderBy not working
Sorting collection using OrderBy not working

Time:11-01

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?

CodePudding user response:

.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);
}

CodePudding user response:

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

  • Related