Come incorporare il campo List <string> in GroupBy ()

Aug 19 2020

Ho un elenco di oggetti Diff. Diff assomiglia a questo

public class Diff
{
    ChangeAction Action // ChangeAction is an Enum
    string Type
    DateTime StartDateTime
    DateTime EndDateTime
    int rateId
    string rateDescription
    List<string> properties
    DayOfWeek day
    List<DaysOfWeek> DaysOfWeek
    DayOfWeek DayOfWeek

}

La mia query LINQ non fa quello che penso che farà. Sto passando in diff.propertiesin GroupBy(), che è una lista e voglio che gruppo quando tutti i valori di stringa in un match lista

var results = diffs
    .GroupBy(diff => new { diff.properties, diff.Action, diff.Type, diff.StartDateTime, 
                           diff.EndDateTime, diff.rateId, diff.rateDescription}) 
    .Select(group => new Diff(
        group.Key.Action,
        group.Key.ScheduleType,
        group.Key.StartDateTime,
        group.Key.EndDateTime,
        group.Key.rateId,
        group.Key.rateDescription,
        group.Key.properties,
        group
            .Select(ts => ts.DayOfWeek)
            .Distinct()
            .OrderBy(dow => dow)
            .ToList()))
    .ToList();

L'unica differenza tra resultse diffsè che il singolare DayOfWeekprecedentemente memorizzato diffsviene ora inserito nel DaysOfWeekcampo plurale (ma solo 1 elemento nell'elenco). Attualmente, lo stesso numero di elementi in entrambi resultse diffs.

Quello che mi piacerebbe vedere nell'elenco dei risultati sono:

  1. Un elenco più breve che si consolida in base alla corrispondenza su tutti i raggruppamenti (inclusi i valori dell'elenco delle proprietà diff.)
  2. Ciò significherebbe anche più di 1 elemento nell'elenco DaysOfWeek.

La mia domanda è:

Come posso modificare la mia query LINQ sopra per vedere cosa voglio vedere results?

Risposte

4 TravisJ Aug 19 2020 at 06:02

Il raggruppamento che stai usando con il tipo anonimo contiene un List<string>che ti fa ottenere un set non raggruppato 1-1.

Hai bisogno di entrambi

  • utilizzare una classe personalizzata per il raggruppamento e l'overload GetHashCodee Equalscome mostrato in questa domanda: Utilizzo di LINQ GroupBy per raggruppare per oggetti di riferimento anziché per oggetti valore

- O -

  • comporre una stringa dai valori, o un sottoinsieme di essi, essendo selected ( diff.properties, diff.Action, diff.Type, diff.startdatetime, diff.enddatetime, diff.rateId, diff.rateDescription) che servirà come chiave univoca con cui raggrupparsi
2 RufusL Aug 19 2020 at 07:16

Alcune delle tue GroupByproprietà sono tipi di riferimento e l'operatore di confronto predefinito per questi tipi è un confronto di riferimento, quindi nessuno di questi corrisponderà mai. Per ovviare a questo, possiamo scrivere il nostro EqualityComparerper la Diffclasse in modo da poterli confrontare a modo nostro:

public class DiffEqualityComparer : IEqualityComparer<Diff>
{
    public bool Equals(Diff first, Diff second)
    {
        if (first == null || second == null) return ReferenceEquals(first, second);

        if (first.Properties == null && second.Properties != null) return false;
        if (first.Properties != null && second.Properties == null) return false;
        if (first.Properties != null && second.Properties != null &&
            !first.Properties.OrderBy(p => p)
                .SequenceEqual(second.Properties.OrderBy(p => p)))
            return false;
        if (!first.Action.Equals(second.Action)) return false;
        if (!string.Equals(first.Type, second.Type)) return false;
        if (!first.Start.Equals(second.Start)) return false;
        if (!first.End.Equals(second.End)) return false;
        if (!first.RateId.Equals(second.RateId)) return false;
        if (!string.Equals(first.RateDescription, second.RateDescription)) return false;

        return true;
    }

    public int GetHashCode(Diff obj)
    {
        var hash = obj.Properties?.Aggregate(0,
            (accumulator, current) => accumulator * 17 + current.GetHashCode()) ?? 0;
        hash = hash * 17 + obj.Action.GetHashCode();
        hash = hash * 17 + obj.Type?.GetHashCode() ?? 0;
        hash = hash * 17 + obj.Start.GetHashCode();
        hash = hash * 17 + obj.End.GetHashCode();
        hash = hash * 17 + obj.RateId.GetHashCode();
        hash = hash * 17 + obj.RateDescription?.GetHashCode() ?? 0;

        return hash;
    }
}

E finalmente possiamo usare questo comparatore personalizzato nel nostro GroupBymetodo:

var results = diffs
    .GroupBy(diff => new DiffEqualityComparer())
    .Select( // rest of code omitted 
1 surprised_ferret Aug 19 2020 at 06:48

L'ho risolto!

Leggere un'altra domanda e i commenti + le risposte in questa domanda mi ha aiutato a capirlo!

public class DiffComparer : IEqualityComparer<Diff>
    {
        public bool Equals(Diff x, Diff y)
        {
            return x.Action == y.Action &&
                x.Type == y.Type &&
                x.StartDateTime == y.StartDateTime &&
                x.EndDateTime == y.EndDateTime &&
                x.rateId== y.rateId &&
                x.rateDescription == y.rateDescription &&
                x.properties.SequenceEqual(y.properties);
        }

        public int GetHashCode(Diff x)
        {
            int hash = 17;

            hash = hash * 23 + x.Action.GetHashCode();
            hash = hash * 23 + x.Type.GetHashCode();
            hash = hash * 23 + x.StartDateTime .GetHashCode();
            hash = hash * 23 + x.EndDateTime.GetHashCode();
            hash = hash * 23 + x.rateId.GetHashCode();
            hash = hash * 23 + x.rateDescription.GetHashCode();

            foreach (string prop in x.properties)
            {
                hash = hash * 31 + prop.GetHashCode();
            }

            return hash;
        }
    }

E ho apportato questa modifica a LINQ:


var results = diffs
    .GroupBy(diff => diff, new DiffComparer()) 
    .Select(group => new Diff(
        group.Key.Action,
        group.Key.ScheduleType,
        group.Key.StartDateTime,
        group.Key.EndDateTime,
        group.Key.rateId,
        group.Key.rateDescription,
        group.Key.properties,
        group
            .Select(ts => ts.DayOfWeek)
            .Distinct()
            .OrderBy(dow => dow)
            .ToList()))
    .ToList();