Jak usunąć duplikaty z listy obiektów

0

Jak usunąć duplikaty z listy obiektów?

1

Np. tak: var newList = list.Distinct();.

0

Jak lista jest obietkowa np mam
Klasa User
private String login;
private String password;

get i set
...

W innej klasie:

public User newUser;

List<User> listUser = new List <User>
listUser.Add(newUser);

czy w tym wypadku mogę użyć Distinct?

1

Możesz również użyć Distinct tylko dobrze wskazać sposób w jaki te obiekty porównujesz:

using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;

class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

class PersonComparer : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        return x.Name.Equals(y.Name) && x.Surname.Equals(y.Surname);
    }

    // Przykład. Jak Ty to zrobisz to już Twoja wola :)
    public int GetHashCode(Person obj)
    {
        return obj.Name.GetHashCode() + obj.Surname.GetHashCode();
    }
}

class Program
{
    public static void Main(string[] args)
    {
        var persons = new List<Person>
        {
            new Person { Name = "Joe", Surname = "First" },
            new Person { Name = "Joe", Surname = "First" },
            new Person { Name = "Anna", Surname = "Someone" },
        };

        persons.Distinct(new PersonComparer()).ToList().ForEach(p => Console.WriteLine("{0} {1}", p.Name, p.Surname));
    }
}

http://ideone.com/b2b8GX

0

A lepszym rozwiązaniem nie będzie Contains(model)?

0

co znaczy lepszym rozwiązaniem? Distinct służy do tego co chcesz, Contains możesz jedynie użyć do zaimplementowania Distinct po swojemu

1 użytkowników online, w tym zalogowanych: 0, gości: 1