How add uniqe element from List to ObservableCollection by Linq

list<string distinct c#
c# list distinct not working
get distinct values from list c# using lambda
c# find duplicates in list of objects
c# remove duplicates from list of objects
c# unique list
linq unique
mvc distinct list

I have a question about check for if object in one List exists in another and if not add them into second list all by Linq. Actually I have two loops with one condition:

 foreach (var p in seznamVlaku.Select(s => s.ProjizdejiciStanicemi)) {
            foreach (var l in p) {
                if(_nodes.Any(a => a.ID != l.Key.ID)){
                    _nodes.Add(new Node() {Name = l.Key.Jmeno, ID = l.Key.ID, X = l.Key.X, Y = l.Key.Y });
                }
            }
        }

It is possible do this faster by Linq query?

I don't think there is a much faster way, you have to check if l already exists in _nodes, and that for each l. If you could optimize that on a higher level I can't tell without knowing what this is doing.

If you simply want a shorter LINQ statement, you can use SelectMany:

foreach(var l in sznamVlaku.SelectMany(s => s.ProjizdejiciStanicemi)
                           .Where(x => _nodes.All(a => a.ID != x.Key.ID)))
    _nodes.Add(new Node() {Name = l.Key.Jmeno, ID = l.Key.ID, X = l.Key.X, Y = l.Key.Y });

Note that I used All instead of Any, because you want to find all l where all nodes have a different ID.

C# Remove Duplicates From List, Eliminate duplicate elements from a List with Distinct, HashSet, or for-loops in an optimal way. Linq; class Item { public int Key; public string Value; } class "Bird​" }); list.Add(new Item() { Key = 10, Value = "Frog" }); // Get distinct items using  I have a object model that has ID, Name and Category properties I have another object model that is an ObservableCollection of my first model I want to get all the unique categories from my collection using Linq, but I am not sure how to do it

  1. You don't need two foreach. Instead use SelectMany.

Your example:

foreach (var p in seznamVlaku.Select(s => s.ProjizdejiciStanicemi))
{
    foreach (var l in p)
    {
    }
}

We can write like and it'd be the same:

foreach (var node in seznamVlaku.SelectMany(list => list.ProjizdejiciStanicemi))
{
}
  1. You can add condition (existing item) add to pipeline of linq query

Code:

foreach (var node in seznamVlaku
    .SelectMany(list => list.ProjizdejiciStanicemi)
    .Where(item => nodes
        .Exists(node => node.ID != item.ID)))
{
    _nodes.Add(new Node() {Name = node.Key.Jmeno, ID = node.Key.ID, X = node.Key.X, Y = node.Key.Y });
}

Get uniqe property list from ObservableCollection using Linq , Find answers to Get uniqe property list from ObservableCollection I want to get all the unique categories from my collection using Linq, Not on the correct framework at all, but I do want to give the points for the work done. Then let’s say you want to populate this from a Linq query (Linq to XML for example). You soon run into the rather large gap becaue, unlike List<T>, ObservableCollection doesn’t have a suitable way to initialise it with a collection (not one that’s suitable for use in a Linq query. Here’s how I fixed it in my project first.

The following code should be considerably faster because it uses hashing instead of nested loops:

// build a HashSet of your key's type (I'm assuming integers here) containing all your current elements' keys in the _nodes ObservableCollection
HashSet<int> hashSet = new HashSet<int>(_nodes.Select(n => n.ID));

foreach (var l in seznamVlaku.SelectMany(s => s.ProjizdejiciStanicemi)) {
    // if you can add the element's ID to the HashSet it hasn't been added before
    if(hashSet.Add(l.Key.ID)) {
        _nodes.Add(new Node() {Name = l.Key.Jmeno, ID = l.Key.ID, X = l.Key.X, Y = l.Key.Y });
    }
}

Various Ways to Get Distinct Values from a List<T> using LINQ, The method above returns a list of Products by adding some dummy data to the List just for the simplicity of this demo. In a real scenario, you may  \$\begingroup\$ @t3chb0t, it's like applying Linq's Select or Where to ObservableCollection, but instead of just getting an IEnumerable you get an INotifyCollectionChanged. The standard library sort-of provides Where with CollectionView , but doesn't (AFAIK) provide Select . \$\endgroup\$ – Peter Taylor Jan 23 '19 at 9:51

https://social.msdn.microsoft.com/Forums/silverlig, In above result you can see the elements are unique because union removed the repeated/duplicate elements from both collections/ list. Questions: The fact that it is a LINQ result might perhaps not be relevant for the question, but I’m mentioning it anyway – since this is the context which has resulted in this question. I run a LINQ query. The result is an; IEnumerable<MyClass> I want to put the result into an ObservableCollection; ObservableCollection<MyClass> How

Use Of Union, Intersect, Distinct And Except In LINQ, Move events in ObservableSelectIterator could be expensive if elements are shifted around near the start of the list, as Remove and Insert will  Adds the elements of the specified collection to the end of the List<T>. The collection whose elements should be added to the end of the List<T>. The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type. The following example demonstrates the AddRange method and various other methods of the

Linq for ObservableCollection, Your task is to merge two lists of objects. The resulting collection should C# programmers often turn to LINQ, and they should! With LINQ you could end up with Then just add it as the second parameter to the constructor. Returns the element at a specified index in a sequence. The type of the elements of source. An IEnumerable<T> to return an element from. The zero-based index of the element to retrieve. The element at the specified position in the source sequence. index is less than 0 or greater than or equal to the number of elements in source.

Comments
  • This _nodes.Any(a => a.ID != l.Key.ID) means 'if there is node that has different id then _nodes.Add(...)'. Is it a typo ? Shouldn't it be: !_nodes.Any(a => a.ID == l.Key.ID) ?
  • You can use IEnumerable.Except() to filter out elements that exist in a different list. NewList.AddRange(OriginalList.Except(TheOtherList));
  • @BradleyUffner that would require a custom equality comparer, or MoreLinq's ExceptBy.
  • Fabian you have right :)
  • Is _nodes a List<T> collection?