繁体   English   中英

如何从列表/集合中获取特定类型的最后一项?

[英]How to get the last item of specific type from a list / collection?

目前,我正在使用Outlook,并且正在遍历项目列表。

这里的问题:我想在foreach循环中询问当前项目是否为最后一项-但我无法解决此类问题。

这是我的代码:

lastAppointmentItem = myAppointmentItems.GetLast();
foreach (Outlook.AppointmentItem myItem in myAppointmentItems)
{
    // Types
    // myAppointmentItems = Outlook.Items
    // myItem = Outlook.AppointmentItem
    if(myItem.Equals(lastAppointmentItem)) { do_something(); }
}

当我运行程序时,我得到一个

System.Runtime.InteropServices.COMException:
// The last element of the list cannot be called

那么我该如何解决我的问题-你们知道吗?

提前致谢!

问候。

我能够使用System.Linq类来获取.Last()方法的使用。 我有下面的示例工作。

namespace StackOverflow
{
   class Program
   {
      static void Main(string[] args)
      {
         List<Test> tests = new List<Test>()
         {
            new StackOverflow.Test()
            {
                id = "test",
                name = "name"
            },
            new StackOverflow.Test()
            {
                id = "test1",
                name = "name1"
            },
            new StackOverflow.Test()
            {
                id = "test2",
                name = "name2"
            },
        };

        var lastItem = tests.Last();
        foreach(Test test in tests)
        {
            if (test.Equals(lastItem))
            {
                Console.WriteLine("last item has been cycled to");
            }
        }
        Console.ReadLine();            
      }
   }

   public class Test
   { 
     public string id { get; set; }
     public string name { get; set; }
   }
}

不要使用从1到myAppointmentItems的“ for”循环的“ foreach”循环。 别忘了对它进行排序( myAppointmentItems.Sort(...) )以具有有意义的顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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