pfinferno pfinferno - 3 months ago 15
C# Question

Best way to hold sets of related elements dynamically added

I have a list of files, and the filenames for those files contain some characters then an underscore, then anything else like so:

test_123.txt


What I'm trying to do is loop through these files, pull out the 'prefix' (the characters up to but not including the
_
, add the prefix to a list if it's not already in the list, and then add the whole filename as an element of that prefix.

That might be confusing so here's an example:

List of file names:

A_ieie.txt
B_ldld.txt
C_test.txt
A_232.txt
B_file2.txt
C_345.txt


So I am looping through these files and get the prefix like so:

string prefix = fileName.Substring(0, fileName.IndexOf('_'));


Now, I check if that prefix is already in a list of prefixes, and if not, add it:

List<string> prefixes = new List<string>();

if (!prefixes.Contains(prefix))
{
prefixes.Add(prefix);
}


So here's the prefixes that would be added to that list:

A //not yet seen, add it to list
B //not yet seen, add it to list
C //not yet seen, add it to list
A //already seen, don't add
B //already seen, don't add
C //already seen, don't add


Okay the above is easy to do, but what about when I want to add the filenames that share a prefix to a list?

Since these are going to be dynamically added and could be anything, I can't make several lists before hand. I thought about have a
List
of
lists
, but is that really the best way to do this? Would a class be ideal?

The end goal of the above example would be something like :

[0][0] = A_ieie.txt //This is the 'A' list
[0][1] = A_232.txt
[1][0] = B_ldld.txt //This is the 'B' list
[1][1] = B_file2.txt
[2][0] = C_test.txt //This is the 'C' list
[2][1] = C_345.txt

Answer

Sounds like you want a Dictionary:

var list = new Dictionary<string, List<string>>();

The Key would be the "prefix" and the Value would be a list of strings (the filenames).

EDIT

If you want the list of filenames to be unique, perhaps a HashSet is a better option:

var list = new Dictionary<string, HashSet<string>>();
Comments