Sorting the data returned by a database
In our project we have a requirement that when a开发者_JAVA技巧 set of records are returned by the database the records should be sorted with respect to the TITLE field in the record. The records will have to be sorted alphabetically but if the title of a record has a number in it then it should come after the records whose title only consists of alphabets.
Details: we are using SQL Server , and c#. The data from the database comes to an Entity class whic forwards the data to other layers.
So, What will be the possible and effective solution for this requirement.
I will assume that you have an object that hold data and have a property TITLE. Consider:
class Entity
{
...
public string TITLE { get; set; }
...
}
You can store these entities in a List<Entity>
and later, when you need, call the Sort
method to sort.
For sorting to happen according to your requirements provide a Comparer
when calling Sort. For more information see: http://msdn.microsoft.com/en-us/library/234b841s.aspx.
In Compare(Entity x, Entity y)
you can compare both entities according to your need.
About comparing the TITLE's
:
Try this Comparison method:
private static int StringComparer(string x, string y)
{
if (!x.AllChar()) return 1;
if (!y.AllChar()) return -1;
return x.CompareTo(y) * -1;
}
public static bool AllChar(this string x)
{
char[] chars = x.ToCharArray();
bool allchar = chars.Any<char>((c) => !char.IsLetter(c));
return !allchar;
}
精彩评论