Philo Philo -4 years ago 70
C# Question

C# Refine class property which is a List<string>

I have a class property:-

public List<string> szTypeOfFileList{get;set;}


As the name suggest, the property stores user selection of types of Files of interest (.txt, .doc, .rtf, .pdf, etc).

I am trying to assess whether there is way I could refine this List as it is being populated by user entries OR, if I should wait for all entries and then call a separate method to refine the property.

What I mean by this is, let's say a particular user input is ".doc/.docx". Currently, this would be stored in the List as a single string item. However I want it to be stored as two items separately. This will keep the code in one place and wont require future modules and such.

private List<string> _szTypeOfFileList = new List<string>();
public List<string> szTypeOfFileList
{
get
{
return _szTypeOfFileList;
}
set
{
// Some kind of validation/refining method here ?? //
}
}


EDIT:-

Because my FileTypeList is coming from a checkboxList, I had to use a different methodology than the answer I accepted (which pointed me in the right direction).

foreach (object itemchecked in FileTypeList.CheckedItems)
{
string[] values = itemchecked.ToString().Split('/');
foreach(var item in values)
TransactionBO.Instance.szTypeOfFileList.Add(item);
}


This part of my code is in the UI class before it is passed on to the Business class.

Answer Source

If you know that it'll always be split with a "/" character, just use a split on the string. Including a simple bit of verification to prevent obvious duplicates, you might do something along the lines of:

string[] values = x.Split('/');
foreach (string val in values) {
    if (!_szTypeOfFileList.Contains(val.ToLower().Trim())) {
        _szTypeOfFileList.Add(val.ToLower().Trim());
    }
}

You can also use an array of characters in place of the '/' to split against, if you need to consider multiple characters in that spot.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download