簡體   English   中英

如何在c#中找到最近的日期?

[英]How to find the closest date in c#?

我正在嘗試顯示與GivenDate相比最接近DateToCompareApmaksasApmers的值(這是一個參考值)

例如:

DateToCompare = 01.01.2022 和 01.01.2021

GivenDate = 01.03.2022

我正在嘗試獲取來自日期 01.01.2022 的值

這是我的代碼:

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())) ;

在這里,我收到Name:[ApmaksasApmērs],Type:[ReferenceValue],Message:[Don't currently support idents of type TimeSpan]

有沒有更好的方法來做到這一點? 提前致謝

嗨,如果DateToCompare是一個數組,那么我們將每個 el 與給定日期之間的差值的絕對值進行比較,並且當值最低時是最接近的日期

這是如何

//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());

這是我所做的:

  1. 為所有元素創建一個列表:

     var saraksts = _nolasītMaksājumusQuery.Nolasīt().Where(x => x.DateToCompare <= vm.GivenDate).ToList();
  2. 從列表中找到最大值:

     var maxDate = list.Max(x=>x.DateToCompare)
  3. 找到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()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM