Domanda

Ho una classe Articoli con proprietà (ID, nome, codice, prezzo) .

L'elenco di elementi è popolato con elementi duplicati.

Per es .:

1         Item1       IT00001        $100
2         Item2       IT00002        $200
3         Item3       IT00003        $150
1         Item1       IT00001        $100
3         Item3       IT00003        $150

Come rimuovere i duplicati nell'elenco usando linq?

È stato utile?

Soluzione

var distinctItems = items.Distinct();

Per abbinare solo alcune delle proprietà, crea un comparatore di uguaglianza personalizzato, ad esempio:

class DistinctItemComparer : IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.Id == y.Id &&
            x.Name == y.Name &&
            x.Code == y.Code &&
            x.Price == y.Price;
    }

    public int GetHashCode(Item obj) {
        return obj.Id.GetHashCode() ^
            obj.Name.GetHashCode() ^
            obj.Code.GetHashCode() ^
            obj.Price.GetHashCode();
    }
}

Quindi usalo in questo modo:

var distinctItems = items.Distinct(new DistinctItemComparer());

Altri suggerimenti

var distinctItems = items.GroupBy(x => x.Id).Select(y => y.First());

Se c'è qualcosa che sta gettando via la tua query Distinct, potresti voler guardare MoreLinq e utilizza l'operatore DistinctBy e seleziona oggetti distinti per ID.

var distinct = items.DistinctBy( i => i.Id );

Ecco come sono riuscito a raggrupparmi con Linq. Spero che sia d'aiuto.

var query = collection.GroupBy(x => x.title).Select(y => y.FirstOrDefault());

Usa Distinct () ma tieni presente che utilizza il comparatore di uguaglianza predefinito per confrontare i valori, quindi se vuoi qualcosa di diverso devi implementare il tuo comparatore.

Vedi http://msdn.microsoft.com/en-us/ library / bb348436.aspx per un esempio.

Hai tre opzioni qui per rimuovere elementi duplicati dal tuo Elenco:

  1. Utilizza un comparatore di uguaglianza personalizzato e quindi usa Distinct (new DistinctItemComparer ()) come @Christian Hayter menzionato.
  2. Usa GroupBy , ma tieni presente in GroupBy dovresti raggruppare per tutte le colonne perché se solo raggruppi per Id non rimuove sempre gli elementi duplicati. Ad esempio, considera il seguente esempio:

    List<Item> a = new List<Item>
    {
        new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
        new Item {Id = 2, Name = "Item2", Code = "IT00002", Price = 200},
        new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
        new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
        new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
        new Item {Id = 3, Name = "Item3", Code = "IT00004", Price = 250}
    };
    var distinctItems = a.GroupBy(x => x.Id).Select(y => y.First());
    

    Il risultato per questo raggruppamento sarà:

    {Id = 1, Name = "Item1", Code = "IT00001", Price = 100}
    {Id = 2, Name = "Item2", Code = "IT00002", Price = 200}
    {Id = 3, Name = "Item3", Code = "IT00003", Price = 150}
    

    Che non è corretto perché considera {Id = 3, Nome = " Item3 " ;, Code = " IT00004 " ;, Price = 250} come duplicati. Quindi la query corretta sarebbe:

    var distinctItems = a.GroupBy(c => new { c.Id , c.Name , c.Code , c.Price})
                         .Select(c => c.First()).ToList();
    

    3. Override Equal e GetHashCode nella classe di elementi:

    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public int Price { get; set; }
    
        public override bool Equals(object obj)
        {
            if (!(obj is Item))
                return false;
            Item p = (Item)obj;
            return (p.Id == Id && p.Name == Name && p.Code == Code && p.Price == Price);
        }
        public override int GetHashCode()
        {
            return String.Format("{0}|{1}|{2}|{3}", Id, Name, Code, Price).GetHashCode();
        }
    }
    

    Quindi puoi usarlo in questo modo:

    var distinctItems = a.Distinct();
    

Un metodo di estensione universale:

public static class EnumerableExtensions
{
    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> enumerable, Func<T, TKey> keySelector)
    {
        return enumerable.GroupBy(keySelector).Select(grp => grp.First());
    }
}

Esempio di utilizzo:

var lstDst = lst.DistinctBy(item => item.Key);
List<Employee> employees = new List<Employee>()
{
    new Employee{Id =1,Name="AAAAA"}
    , new Employee{Id =2,Name="BBBBB"}
    , new Employee{Id =3,Name="AAAAA"}
    , new Employee{Id =4,Name="CCCCC"}
    , new Employee{Id =5,Name="AAAAA"}
};

List<Employee> duplicateEmployees = employees.Except(employees.GroupBy(i => i.Name)
                                             .Select(ss => ss.FirstOrDefault()))
                                            .ToList();

Prova questo metodo di estensione. Speriamo che questo possa aiutare.

public static class DistinctHelper
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        var identifiedKeys = new HashSet<TKey>();
        return source.Where(element => identifiedKeys.Add(keySelector(element)));
    }
}

Utilizzo:

var outputList = sourceList.DistinctBy(x => x.TargetProperty);

Quando non vuoi scrivere IEqualityComparer puoi provare qualcosa come segue.

 class Program
{

    private static void Main(string[] args)
    {

        var items = new List<Item>();
        items.Add(new Item {Id = 1, Name = "Item1"});
        items.Add(new Item {Id = 2, Name = "Item2"});
        items.Add(new Item {Id = 3, Name = "Item3"});

        //Duplicate item
        items.Add(new Item {Id = 4, Name = "Item4"});
        //Duplicate item
        items.Add(new Item {Id = 2, Name = "Item2"});

        items.Add(new Item {Id = 3, Name = "Item3"});

        var res = items.Select(i => new {i.Id, i.Name})
            .Distinct().Select(x => new Item {Id = x.Id, Name = x.Name}).ToList();

        // now res contains distinct records
    }



}


public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top