Reputation: 1148
Good day 4 u all
I have a list of objects
My objects like
Product = "iPhone";
Category = "SmartPhone";
Product = "HP";
Category = "PC";
Product = "HTC";
Category = "SmartPhone";
And I insert each object into my test so its like
List<Myobject> MyList = new List<Myobject>();
And now I need to sord/order MyList by the category
As I need my list to show the SmartPhone category first then other
Upvotes: 28
Views: 50076
Reputation: 111940
You can use List.Sort
l.Sort((p, q) => p.Category.CompareTo(q.Category));
The advantage over the LINQ OrderBy
is that you'll order the list in-place instead of generating an IOrderedEnumerable<T>
that then you have to re-transform in a List<T>
.
Upvotes: 39
Reputation: 700850
You can use the Sort
method and a custom comparison, to sort by category (descending) and then by product (ascending):
MyList.Sort((a, b) => {
// compare b to a to get descending order
int result = b.Category.CompareTo(a.Category);
if (result == 0) {
// if categories are the same, sort by product
result = a.Product.CompareTo(b.Product);
}
return result;
});
If you want to single out smartphones, and then sort ascending:
MyList.Sort((a, b) => {
int result = (a.Category == "SmartPhone" ? 0 : 1) - (b.Category == "SmartPhone" ? 0 : 1);
if (result == 0) {
result = a.Category.CompareTo(b.Category);
if (result == 0) {
result = a.Product.CompareTo(b.Product);
}
}
return result;
});
Upvotes: 7
Reputation: 56984
Check out the LINQ OrderBy extension method.
MyList.OrderBy (p => p.Category);
If you need a more complex way to sort the categories, you could create a class which implements the IComparer interface, and implement your sort logic in it.
public class SmartphonesFirst : IComparer<Product>
{
const string Smartphone = "Smartphone";
public int Compare( Product x, Product y )
{
if( x.Category == Smartphone && y.Category != Smartphone )
{
return -1;
}
if( y.Category == Smartphone && x.Category != Smartphone )
{
return 1;
}
else
{
return Comparer<String>.Default.Compare (x.Category, y.Category);
}
}
}
You can do it without using LINQ:
var l = new List<Product> ();
l.Add (new Product ()
{
Name = "Omnia 7",
Category = "Smartphone"
});
l.Add (new Product ()
{
Name = "Mercedes",
Category = "Car"
});
l.Add (new Product ()
{
Name = "HTC",
Category = "Smartphone"
});
l.Add (new Product ()
{
Name = "AMD",
Category = "CPU"
});
l.Sort (new SmartphonesFirst ());
foreach( var p in l )
{
Console.WriteLine (String.Format ("{0} : {1}", p.Category, p.Name));
}
Or, with using LINQ:
var l = new List<Product> ();
l.Add (new Product ()
{
Name = "Omnia 7",
Category = "Smartphone"
});
l.Add (new Product ()
{
Name = "Mercedes",
Category = "Car"
});
l.Add (new Product ()
{
Name = "HTC",
Category = "Smartphone"
});
l.Add (new Product ()
{
Name = "AMD",
Category = "CPU"
});
var sorted = l.OrderBy (p => p, new SmartphonesFirst ());
foreach ( var p in sorted )
{
Console.WriteLine (String.Format ("{0} : {1}", p.Category, p.Name));
}
Upvotes: 23