Reputation: 107
I had some help earlier on another post to remove the file extension in my dropdown list. I now need to remove duplicates. This is the current before and after:
Before:
video-1.mp4
video-1.ogv
video-1.webm
After: (Current code)
video-1
video-1
video-1
What I want:
video-1
Here is my code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
var item = new ListItem(Path.GetFileNameWithoutExtension(filePath), filePath);
if (!files.Contains(item))
files.Add(item);
}
DropDownList1.DataSource = files;
DropDownList1.DataTextField = "";
DropDownList1.DataValueField = "";
DropDownList1.DataBind();
}
}
Upvotes: 0
Views: 140
Reputation: 27861
I am assuming that you want to keep the filePath
(at least for some of the files) and store it as the value of the ListItem
as shown by your code.
You can use a Dictionary like this:
Dictionary<string,string> filenames = new Dictionary<string, string>();
foreach (string filePath in filePaths)
{
var file_name_without_extension = Path.GetFileNameWithoutExtension(filePath);
if(filenames.ContainsKey(file_name_without_extension))
continue;
filenames.Add(file_name_without_extension, filePath);
}
List<ListItem> files = filenames.Select(x => new ListItem(x.Key, x.Value)).ToList();
Upvotes: 1
Reputation: 1864
LINQ's extension method .Distinct()
will help. You may need to manually add using System.Linq;
Don't forget that it will return new collection without duplict elements instead of modifying current one.
Upvotes: 1