什么是处理在一个又一个发生的列表中查找项目的最佳方法?

时间:2009-09-09 15:54:25

标签: c# collections .net-2.0

我有一个这样的课程

public class HistoryEntry
{
    DateTime Date{ get; protected set; }
    HistoryType EntryType { get; protected set; }
}

public enum HistoryType
{
    Cancelled,
    Cleared,
    Redeemed,
    Refunded
}

我有一个这些历史记录条目的无序列表,我确实存在语句,以查看列表中是否存在条目。

return Entries.Exists(e => e.EntryType == HistoryEntryType.Cancelled);

现在我需要更改此方法,以便此方法返回最后清除条目的TimeStamp后是否存在已取消条目(如果存在),否则只返回是否存在已取消条目

我仅限于.Net 2.0中提供的选项

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

    private bool ContainsCanceled(List<HistoryEntry> list)
    {
        list.Sort();
        int index = list.FindLastIndex(delegate(HistoryEntry h) { return h.HistoryType == HistoryType.Cleared; });
        for (int i = index >= 0? index : 0; i < list.Count; i++)
        {
            if (list[i].HistoryType == HistoryType.Cancelled)
            {
                return true;
            }
        }

        return list.Exists(delegate(HistoryEntry h) { return h.HistoryType == HistoryType.Cancelled; });
    }

我正在使用C#2.0语法...

哦,还有一件事,请确保您的HistoryEntry类实现了IComparable:

public class HistoryEntry : IComparable<HistoryEntry>
{
    public DateTime Date { get; set; }
    public HistoryType HistoryType { get; set; }

    public int CompareTo(HistoryEntry other)
    {
        return this.Date.CompareTo(other.Date);
    }

}

答案 1 :(得分:0)

搜索列表中匹配条目的索引,这需要进行两次搜索。

int p = Entries.FindIndex(e => e.EntryType == HistoryEntryType.Cleared);
if (p < 0)
    p = 0;
p = Entries.FindIndex(p, e => e.EntryType == HistoryEntryType.Cancelled);
return (p >= 0);

请参阅 http://msdn.microsoft.com/en-us/library/efasdh0s.aspx

相关问题