开发者

how to reverse the order of words in query or c#

i have stored in the database as

location

India,Tamilnadu,Chennai,A开发者_如何学Pythonnnanagar

while i bind in the grid view it ll be displaying as 'India,Tamilnadu,Chennai,Annanagar' this format.

but i need to be displayed as 'Annanagar,Chennai,Tamilnadu,India' in this format. how to perform this reverse order in query or in c#

note: this is stored under one column as 'India,Tamilnadu,Chennai,Annanagar' with comma separated.


I believe location example provided by OP is just one result from DB and he is looking for something like this:

string location = "India,Tamilnadu,Chennai,Annanagar";
string[] words = location.Split(',');

Array.Reverse(words);

string newlocation = String.Join(",", words);

Console.WriteLine(newlocation); // Annanagar,Chennai,Tamilnadu,India


In SQL Syntax:

SELECT location FROM locations ORDER BY location ASC // server side sorting

Or if you have your result in a DataTable you could use this:

table.DefaultView.Sort = "location ASC"; // client side in-memory sorting


Using C# we have:

var arr = new[] { "India", "Tamilnadu", "Chennai", "Annanagar" };

Using LINQ:

var q = from location in arr
        orderby location ascending // or descending
        select location;

Using extension methods:

var q = arr.OrderBy(l => l);
var q = arr.OrderByDescending(l => l);


In SQL you could use the order by query.

SELECT * FROM location
ORDER BY City

This will return the results ordered alphabetically by the City column.

If you wanted to reverse the order so it would be ordered from Z -> A you would do

ORDER BY City DESC

It is generally always a good idea to apply some kind of ordering in your queries that will be used for display, otherwise the results come back in a random non-deterministic order which is rarely what you want.


Are you asking how to make the string Locality,City,State,Country when you have it stored in the reverse order? then you cant do that using sorting.

If you have all the values stored in a single field as comma separated values, In C#, you can split the string by Comma as the separator and then join it again by appending the items in the reverse order by using comma as separator.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜