Mehdi LAMRANI
Mehdi LAMRANI

Reputation: 11597

Updating a WPF's ObservableCollection content

What is the most convenient to update an ObservableCollection's data based on some fields ? I can think of many ways to do it (Linq, iterations...) but I was wondering if somebody has something proofed to offer.

public ObservableCollection<CCData> CCDataList =
    new ObservableCollection<CCData>();

public class CCData : INotifyPropertyChanged
{
    public string Symbol { get; set; }
    public string LastTick { get; set; }

    //INotifyPropertyChanged stuff here...
}

CCDataList.Add(new CCData
        {
            Symbol = "EUR/USD",
            Time = "12:21:58"
        });

 CCDataList.Add(new CCData
        {
            Symbol = "AUD/JPY",
            Time = "12:25:40"
        });

Example
Let's suppose I want to look in the collection for the symbol entry "EUR/USD" and update the time entry. How to achieve this ?

Upvotes: 0

Views: 189

Answers (2)

Harish
Harish

Reputation: 1

dude the best way from performance point of view is to iterate using for loop and the first time you encounter the desired value update it and use the break to terminate the loop. foreach and enumerable class extended functions make use of extra resources like enumerator. from codeing point of view they are efficient but from performance point of view simplee looping is the best.

Upvotes: 0

Chris
Chris

Reputation: 3162

There are many ways to do it as you've mentioned. However I still prefer Linq hands down and would do something like this. Granted this isn't coded very defensively but you get the idea.

CCDataList.Where(c => c.Symbol == "EUR/USD").First().Time = DateTime.Now;

As you could create a simple method to update the property for you

public void UpdateCurrencyTime(string currencySymbol, DateTime time)
{
   var item = CCDataList.Where(c => c.Symbol == currencySymbol).FirstOrDefault();
   if(item != null)
       item.Time = time;
}

Upvotes: 2

Related Questions