Arithmomaniac
Arithmomaniac

Reputation: 4804

Trimming entries in a List<string> after every write

I'm doing repeated work on a List<string> to build an instance of MyClass, but for simplicity's sake (there are a lot of regular expressions and IndexOf operations involved), I have to currently Trim each line after every operation:

static MyClass Populate (\List<str> strList)
{
    MyClass myClassInstance = new MyClass();
    Operation1(ref strList, myClassInstance);
    TrimAllLines(strList);
    Operation2(ref strList, myClassInstance);
    TrimAllLines(strList);
    //...
    return myClassInstance;
}

Is there a good way (preferably a drop-in replacement ) to make it so that every time I write to strList, each string within is automatically trimmed?

Things I've toyed with:

Upvotes: 0

Views: 323

Answers (2)

br1
br1

Reputation: 313

You could use

System.Collections.ObjectModel.ObservableCollection

instead of your List

And do something like:

    ObservableCollection<string> myCollection = new ObservableCollection<string>();

    void Init()
    {
        myCollection.CollectionChanged +=myCollection_CollectionChanged;
    }

    void myCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        myCollection.CollectionChanged -= myCollection_CollectionChanged;
        //could be a delete / clear / remove at operation
        if (e.NewItems != null)
        {
            for (int i = 0; i < e.NewItems.Count; i++)
            {
                string str = (string)e.NewItems[i];
                //the added value could be null
                if (str != null)
                {
                    string trimmed = str.Trim();                        
                    if (!trimmed.Equals(str))
                    {
                        myCollection[e.NewStartingIndex + i] = str.Trim();
                    }
                }
            }
        }
        myCollection.CollectionChanged += myCollection_CollectionChanged;
    }

after that, each time the ObservableCollection will be modified, the added items will be automatically trimmed.

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 660297

Is there a good way (preferably a drop-in replacement ) to make it so that every time I write to strList, each string within is automatically trimmed?

You don't want the behavior of List<T>, so don't use List<T>. Instead, make your method take IList<T> and provide an implementation of that interface that does what you want.

The implementation might simply be a wrapper class that contains a private List<T>.

See also this related question:

How do I override List<T>'s Add method in C#?

Upvotes: 13

Related Questions