Probabilmente flags
è una lista di tipo di riferimento, e distinto non funziona come ci si aspetta! Questo perché Distinct() non funziona sul valore della bandiera nella lista, ma sui suoi riferimenti di memoria (che sono tutti diversi).
Devi scrivere una classe di confronto che insegna a Distinto come confrontare lo stesso flag. Supponiamo di avere questa classe bandiera:
public class flag
{
public string Name { get; set; }
public string Code { get; set; }
}
si dovrebbe creare una classe di confronto come questo:
class FlagComparer : IEqualityComparer<flag>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(flag x, flag y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Code == y.Code && x.Name == y.Name;
}
}
e la chiamata la sua dichiarazione:
List distinctFlags = flags.Distinct(new FlagComparer()).ToList();
In questo modo, metodo distinto sa esattamente come confrontare l'istanza della bandiera uguale.
UPDATE
Sulla base di tuo commento, se vuoi anche seguire il mio suggerimento, si dovrebbe scrivere la base di confronto come segue:
class FlagComparer : IEqualityComparer<flag>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(flag x, flag y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.HostID == y.HostID && x.RuleID == y.RuleID && x.Flag == y.Flag && x.FlagValue == y.FlagValue;
}
}
Naturalmente, ogni proprietà deve essere un tipo di valore .
dare uno sguardo qui per chiarire se stessi:
Quali sono i tuoi valori di input e cosa vi aspettate come output? –
Si trova all'interno o all'esterno di dbcontext? Mostra altro codice per favore. E se puoi, dai un esempio dei dati prima e dopo la trasformazione. –
Raggruppali e scegli un vincitore. http://stackoverflow.com/questions/489258/linq-distinct-on-a-particular-property/491832#491832 –