简体   繁体   中英

Comparing generic list collection in Blazor component

I want to customize action if the generic list collection is changed. When i click the ChangeDate button, the dates cleared and ViewerComp Onparameter method will trigger. I know its a reference type. so the value remains same. Is it possible to check difference?

Index

<button @onclick="ChangeDates">Change dates</button>

<ViewerComp Dates="@dates">

</ViewerComp>

@code{
    private List<DateClass> dates = new List<DateClass>()
    {
        new DateClass(){StartDate = new DateTime(2021,12,01), EndDate = new DateTime(2021,12,21)}
    };

    private void ChangeDates()
    {
        dates.Clear();
    }
}

ViwerComp

<div>
        @foreach (DateClass date in Dates)
        {
            <div> @(date.EndDate - date.StartDate).Days</div>
        }
</div>

@code {
    [Parameter]
    public List<DateClass> Dates { get; set; }

    private List<DateClass> dates{ get; set; }

    protected override void OnInitialized()
    {
        dates = Dates;
    }

    protected override void OnParametersSet()
    {
        if(dates != Dates){
            // here i want to customize
        }
    }
}

DateClass

public class DateClass
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

Inherit and Implement the IEquatable for your DateClass and use the LINQ SequenceEqual to compare both.

public class DateClass : IEquatable<DateClass>
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    
   public bool Equals(DateClass other)
   {
      if (other == null)
         return false;

      if (this.StartDate == other.StartDate && this.EndDate == other.EndDate)
         return true;
      else
         return false;
   }

   public override bool Equals(Object obj)
   {
      if (obj == null)
         return false;

      DateClass dateClassObj = obj as DateClass;
      if (dateClassObj == null)
         return false;
      else
         return Equals(dateClassObj);
   }

   public override int GetHashCode()
   {
      return (StartDate, EndDate).GetHashCode();
   }
}

For Comparison, using the SequenceEqual with OrderBy to make both the List been ordered in same way.

dates.OrderBy(x => x.StartDate).SequenceEqual(Dates.OrderBy(x => x.StartDate))

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM