0

I working with WPF and I have an Observablecollection<MyObj>, and myObj class is:

MyObject
{
string happenAtMonth;
int value;
}

happendAtMonth is the name of the month. my observableCollection (MyObColl) will have these values for example:

MyObColl.Add(new MyObj("October", 3));
MyObColl.Add(new MyObj("January", 450));
MyObColl.Add(new MyObj("June", 15));
MyObColl.Add(new MyObj("Febraury", 125));

I need to sort this MyObColl by month The output should be like:

Value was 450 in January
Value was 125 in Febraury
Value was 15 in June
Value was 3 in October

How I would achieve this and sort with ObservableCollection by Month name? Thank you

Alaa'
  • 487
  • 3
  • 7
  • 16
  • Possible duplicate of [How do I sort an observable collection?](https://stackoverflow.com/questions/1945461/how-do-i-sort-an-observable-collection) – Martin Liversage Jan 10 '18 at 07:46
  • Do you want to sort the collection so whatever is bound to it sees the sorted sequence? In that case all the answers provided so far does not answer your question. They just create an `IEnumerable` that is sorted and the original `ObservableCollection` is not changed. Instead you should have a look at [How do I sort an observable collection?](https://stackoverflow.com/questions/1945461/how-do-i-sort-an-observable-collection) which this question is then a duplicate of. – Martin Liversage Jan 10 '18 at 07:51

3 Answers3

3

This parses the months in string format to their integer value and orders them:

var values = MyObColl.OrderBy( o => DateTime.ParseExact( o.Month , "MMMM" , CultureInfo.InvariantCulture ).Month )
    .Select( o => $"Value was {o.Value} in {o.Month}" );

foreach ( var value in values )
    Console.WriteLine( value );
Sievajet
  • 3,443
  • 2
  • 18
  • 22
1

You would need to provide a connection between the string of the month and the index of it. For example:

var months = new Dictionary<string, int>()
{
  {"January", 0},
  {"February", 1}
  //...
};
MyObjColl.OrderBy(x => months[x.happenAtMonth]);

or a better way might be to define an enum:

public enum Month
{
  January = 1,
  February = 2,
  //...
}

and change the definition of your object to:

public class MyObject
{
  public Month HappenAtMonth { get; set; }
  public int Value { get; set; }
}

then:

MyObjColl.OrderBy(x => x.HappenAtMonth);
0

Try this:

MyObjColl= new ObservableCollection<DataConcept>(MyObjColl.OrderBy(i => i.HappenAtMonth));
4est
  • 3,010
  • 6
  • 41
  • 63