Home c# How to better convert List & lt; T & GT; in ObservableCollection...

How to better convert List & lt; T & GT; in ObservableCollection & lt; T & GT; and vice versa?




I do this:

  1. Create a new ObservableCollection & lt; T & GT;
  2. Rubbit List & lt; T & GT; in Foreach and at each iteration add to ObservableCollection list element

It seems to me that it is not “chic.” How to make this task “chic”?

Will there be a good version of writing extension for this case?

Answer 1, Authority 100%

In essence, everything depends on how you will handle these objects.

  • If you just need to do from List & lt; T & GT; ObservableCollection & lt; T & GT; , we can see the documentation (LIST & LT; T & GT; OBSERVACOLLECTION & LT; T & GT; ) and immediately it will be seen that we can simply pass through the desired Ienumerable & lt; T & GT; ).

    var list = new list & lt; string & gt; ();
    var Observable = New ObservableCollection & lt; String & GT; (List);
  • If you have a certain transformation logic, then you can already make a extension method that will return the specified type. For example, create an extension method that returns ObservableCollection & LT; T & GT; and as logic, we will make it so that it returned only N elements taken from the input list:

    static class extensions
      Public Static ObservableCollection & LT; T & GT; TakeToobServable & lt; T & GT; (This ienumerable & lt; t & gt; enumerable, int count)
        = & gt; New ObservableCollection & LT; T & GT; (Enumerable.Take (Count));


    var observable = new list & lt; string & gt; (). TakeToobServable (10);

In general, see yourself, as you need to implement.
Good luck in learning C #!

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions