C# - sorting by a property

后端 未结 3 1270
梦谈多话
梦谈多话 2021-01-27 19:22

I am trying to sort a collection of objects in C# by a custom property. (For context, I am working with the Twitter API using the Twitterizer library, sorting Direct Messages in

3条回答
  •  梦谈多话
    2021-01-27 20:03

    It sounds to me like mlorbetske was correct in his interpretation of your question. It sounds like you want to do grouping rather than sorting. I just went at the answer a bit differently

    var originalList = new[] { new { Name = "Andy", Label = "Junk" }, new { Name = "Frank", Label = "Junk" }, new { Name = "Lisa", Label = "Trash" } }.ToList();
    
    var myLists = new Dictionary>();
    
    originalList.ForEach(x =>
        {
            if (!myLists.ContainsKey(x.Label))                
                myLists.Add(x.Label,new List());
            myLists[x.Label].Add(x);
    
        });
    
        

    提交回复
    热议问题