开发者

Sorting object list by string property C# [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Sorting a list using Lambda/Linq to objects

C# List<> OrderBy Alphabetical Order

How do I go about sorting a list of objects in alphabetical order by a string proper开发者_开发百科ty.

I have tried implementing IComparable on the property but I only figured out how to sort on the first character (using char).

EDIT: Here is some sample code.

class MyObject {
    public string MyProperty {get;set;}
}

List<MyObject> sampleList = new List<MyObject>();    

MyObject sample = new MyObject();
sample.MyProperty = "Aardvark";

MyObject sample2 = new MyObject();
sample2.MyProperty = "Zebra";

sampleList.Add(sample);
sampleList.Add(sample2);

sampleList.Sort(); // or something similar

foreach (var item in sampleList) {
    Console.WriteLine(item.MyProperty);
}

Should output Aardvark and Zebra (in alphabetical order).

Thanks!


You can do it using Comparision delegate, using Sort(Comparision<T> comparision) overload.

list.Sort((a, b) =>  a.StringProperty.CompareTo(b.StringProperty));


You can get a sorted IEnumerable<MyObject> like so:

var sortedQuery = sampleList.OrderBy(x => x.MyProperty);

You can then either convert the query to a list like so:

var sortedList = sortedQuery.ToList();

Or, you can just iterate through the items:

foreach (var obj in sortedQuery)
    Console.WriteLine(obj.MyProperty);


Assuming that your collection implements the IEnumerable interface, you can simply call the OrderBy method on your collection:

myCollection.OrderBy(c => c.Property);


var list = new List<SomeClass>();
// add some instances of SomeClass to list
list.Sort((x, y) => x.SomeProperty.CompareTo(y.SomeProperty));


Convert the code to C# ,

If you have an list object ABC with a string property S for each objects in the list ,

Dim Mylist As New List(Of ABC)

    Dim a = From i In Mylist _
           Order By i.S Ascending

you will have teh result in a , put on a iterator .


Be sure to include System.Collections.Generic and System.Linq.

    List<myItemType> lst = new List<myItemType>();
    return lst.OrderBy(i => i.StringPropertyName);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜