Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

Order files/list before binding them to gridview asp.net C#

Hi I have something like the code below, I want to sort/order the files in the folder lets say by name of the file in asc or dsc order, before binding to the gridview:

string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
                    List<ListItem> files = new List<ListItem>();

                foreach (string filePath in filePaths)
                {
                    files.Add(new ListItem(Path.GetFileName(filePath), filePath));
                }
           
                GridView1.DataSource = files;
                GridView1.DataBind();
question from:https://stackoverflow.com/questions/65672142/order-files-list-before-binding-them-to-gridview-asp-net-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply order by after foreach loop

 files = files.OrderBy(x => x.Text).ToList();

For Order by descending

files = files.OrderByDescending(x => x.Text).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...