Order C# list alphabetically

断了今生、忘了曾经 提交于 2019-12-25 02:12:35

问题


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:


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();


来源:https://stackoverflow.com/questions/19897646/order-c-sharp-list-alphabetically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!