locked
Sorting a list in C# based on a particular value in the item RRS feed

  • Question

  • Hi,

    I have a list of items where in each item has two data.

    Each item has a string and a double value and the double value could sometimes be same across the list items

    I want to sort the list items in ascending order based on the double value the list item contains.

    I know that the list has some functions but could not find it properly.

    Can somebody tell how to perform this.

    Monday, September 30, 2013 8:51 AM

Answers

  • void OrderTest()
            {
                //this.player.Source = new Uri("ms-appx:///Assets/recit24bit.flac", UriKind.Absolute);             
                //this.player.Source = new Uri("ms-appx:///Assets/Stellardrone - Aurora.mp3", UriKind.Absolute); 
    
                var list = new List<MyClass>()
                {
                    new MyClass { strValue = "s1", dobValue = 1},
                    new MyClass { strValue = "a2", dobValue = 4},
                    new MyClass { strValue = "d3", dobValue = 1.5},
                    new MyClass { strValue = "g4", dobValue = 1.9},
                    new MyClass { strValue = "asdasd", dobValue = 9.7},
                    new MyClass { strValue = "fefes1", dobValue = 5.7},
                };
    
                var ordered = list.OrderBy(a => a.dobValue);
            }
    
    

    model:

    public class MyClass
        {
            public string strValue { get; set; }
            public double dobValue { get; set; }
        }

    Monday, September 30, 2013 9:08 AM

All replies

  • void OrderTest()
            {
                //this.player.Source = new Uri("ms-appx:///Assets/recit24bit.flac", UriKind.Absolute);             
                //this.player.Source = new Uri("ms-appx:///Assets/Stellardrone - Aurora.mp3", UriKind.Absolute); 
    
                var list = new List<MyClass>()
                {
                    new MyClass { strValue = "s1", dobValue = 1},
                    new MyClass { strValue = "a2", dobValue = 4},
                    new MyClass { strValue = "d3", dobValue = 1.5},
                    new MyClass { strValue = "g4", dobValue = 1.9},
                    new MyClass { strValue = "asdasd", dobValue = 9.7},
                    new MyClass { strValue = "fefes1", dobValue = 5.7},
                };
    
                var ordered = list.OrderBy(a => a.dobValue);
            }
    
    

    model:

    public class MyClass
        {
            public string strValue { get; set; }
            public double dobValue { get; set; }
        }

    Monday, September 30, 2013 9:08 AM
  • Another alternative could be (with reference to Oleg's class)

    list.Sort((x, y) => x.dobValue.CompareTo(y.dobValue)); which does an inplace sorting


    Nazia

    Monday, September 30, 2013 12:33 PM