gpt4 book ai didi

c# - 使用 linq 获取列表项中的日期差异

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:40 25 4
gpt4 key购买 nike

我有一个约会列表,我想在当前约会开始时间和上次约会结束时间之间做一个差异,以确保没有差异。如果有添加假约会。

我目前的实现是...

public ObservableCollection<Appointment> FillGaps()
{
var appointments = this.Appointments.OrderByDescending(s => s.EndDate).ToList();

for (int i = 0; i < appointments.Count() - 1; i++)
{
var now = appointments[i];

var previous = appointments[i + 1];

if((now.StartDate.Value - previous.EndDate.Value).Days > 1)
{
// add a new appointment between this period
appointments.Add(new Appointment()
{
StartDate = previous.EndDate.Value.AddDays(1),
EndDate = now.StartDate.Value.AddDays(-1),
IsCurrent = false
});
}
}

return appointments.ToObservableCollection();
}

是否有更好或更通用的方法来做到这一点?

根据要求...添加 ToObservable 的实现...

 /// <summary>
/// The to observable collection.
/// </summary>
/// <param name="coll">
/// The collection.
/// </param>
/// <typeparam name="T"> Object T
/// </typeparam>
/// <returns>
/// The <see cref="ObservableCollection"/>.
/// </returns>
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll)
{
var c = new ObservableCollection<T>();
foreach (var e in coll)
{
c.Add(e);
}

return c;
}

Appointment 类没有什么特别的。

/// <summary>
/// The Appointment.
/// </summary>
[Serializable]
public class Appointment
{
public Appointment()
{
this.IsFake = false;
}


/// <summary>
/// Gets or sets the start date.
/// </summary>
public DateTime? StartDate { get; set; }

/// <summary>
/// Gets or sets the end date.
/// </summary>
public DateTime? EndDate { get; set; }

/// <summary>
/// Gets or sets the Is Fake
/// </summary>
public bool IsFake { get; set; }

}

最佳答案

不知道 this.Appointments 属性是如何实现的,或者 ToObservableCollection 扩展方法的参数是什么,很难想出最有效的解决方案。但是,这样的事情应该有效:

private static IEnumerable<Tuple<T, T>> ListPairs<T>(IEnumerable<T> source)
{
using (var enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext()) yield break;

T previous = enumerator.Current;
while (enumerator.MoveNext())
{
T current = enumerator.Current;
yield return new Tuple<T, T>(previous, current);
previous = current;
}
}
}

public ObservableCollection<Appointment> FillGaps()
{
var gaps = ListPairs(this.Appointments.OrderByDescending(s => s.EndDate))
.Where(pair => (pair.Item1.StartDate.Value - pair.Item2.EndDate.Value).Days > 1)
.Select(pair => new Appointment
{
StartDate = pair.Item2.EndDate.Value.AddDays(1),
EndDate = pair.Item1.StartDate.Value.AddDays(-1),
IsCurrent = false,
});

// NB: Assumes "this.Appointments" is a cheap call;
// Also assumes you don't need the results in any particular order.
return this.Appointments.Concat(gaps).ToObservableCollection();
}

关于c# - 使用 linq 获取列表项中的日期差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17154352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com