skip to Main Content

I am trying to display the values of ApmaksasApmers (which is a Reference Value) which are closest to DateToCompare in comparison to GivenDate

For example:

DateToCompare =01.01.2022 and 01.01.2021

and GivenDate = 01.03.2022

I am trying to get the values which come from date 01.01.2022

Here is my code:

vm.ApmaksasApmērs.LookupSource  = _nolasītMaksājumusQuery.Nolasīt()
                    .OrderBy(x => x.DateToCompare.Value > vm.GivenDate.Value ? vm.GivenDate.Value - x.DateToCompare.Value : x.DateToCompare.Value - vm.GivenDate.Value)
                    .Select(x => new KeyValuePair<Guid?, string>(x.Id, x.ApmaksasApmērs +" (" + x.PersonasLīdzmaksājumsProcentos + "%)".ToString())) ;

Here I am geting an error of Name:[ApmaksasApmērs],Type:[ReferenceValue],Message:[Don't currently support idents of type TimeSpan]

Is there a better way of doing this? Thanks in advance

2

Answers


  1. Chosen as BEST ANSWER

    Here is what I did :

    1. Create a list for all of the elements:

      var saraksts =  _nolasītMaksājumusQuery.Nolasīt().Where(x => x.DateToCompare <= vm.GivenDate).ToList();
      
    2. Find the max value from the list:

      var maxDate = list.Max(x=>x.DateToCompare)
      
    3. Find all of the elements where MaxDate == DateToCompare:

      vm.ApmaksasApmērs.LookupSource = list.Where(x => x.DateToCompare== maxDate).Select(x => new KeyValuePair<Guid?, string>(x.Id, x.ApmaksasApmērs +" (" + x.PersonasLīdzmaksājumsProcentos + "%)".ToString()));
      

  2. Hi if DateToCompare is an array then we compare the absolute value of difference between each el with the given date and when the value is lowest that’s the closest date

    Here is how

    //adding some data
    DateTime[] DateToCompare =  {
        new DateTime(2001, 05,05),
        new DateTime(2022,01,01),
        new DateTime(2021,01,01)
        };
    DateTime GivenDate = new DateTime(2022, 05, 02);
    
    //Get the absolute value of diference between first el and given date
    TimeSpan span = abs(DateToCompare[0] - GivenDate);
    
    DateTime closestDate = DateToCompare[0];
    //new we check each el if the dif is lower
    for (int i = 1; i < DateToCompare.Length; i++)
    {
        if (abs(GivenDate - DateToCompare[i]) < span)
        {
            span = abs(GivenDate - DateToCompare[i]);
            closestDate = DateToCompare[i];
        }
    }
    //get absolute value
    TimeSpan abs(TimeSpan t)
    {
        return (t.TotalSeconds >= 0) ? t : -t;
    }
    Console.WriteLine(closestDate.ToShortDateString());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search