Order C# list alphabetically

2019-08-28 00:53发布

I am using to following code to get data from a Web Api and populate it in a list.

HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync("http://localhost:12345/api/items");

var info = new List<SampleDataGroup>();


            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

               var item = JsonConvert.DeserializeObject<dynamic>(content);


                foreach (var data in item)
                {
                      var infoSect = new info
                            (

                                (string)data.Id.ToString(),
                                (string)data.Name,
                                (string)"",
                                (string)data.PhotoUrl,
                                (string)data.Description

                            );
                                 info.Add(infoSect);
                }
             }
            else
            {
                MessageDialog dlg = new MessageDialog("Error");
                await dlg.ShowAsync();
            }


            this.DefaultViewModel["Sections"] = info;

How do I order this alphabetically by Name? So that the results shown are ordered from A-Z by its Name.

1条回答
疯言疯语
2楼-- · 2019-08-28 01:51

I would suggest you try this:

var sorted = info.OrderBy(i => i.Name);

This will return sorted data, ordered by the field chosen in the expression passed to the OrderBy method. The default comparison for string data will be alphabetic sorting, which should be sufficient for your needs.

If you require a List to be returned for assigning to DefaultViewModel["Sections"], you can do:

this.DefaultViewModel["Sections"] = info.OrderBy(i => i.Name).ToList();
查看更多
登录 后发表回答