【问题标题】:How to get the last item of specific type from a list / collection?如何从列表/集合中获取特定类型的最后一项?
【发布时间】:2018-05-17 03:17:30
【问题描述】:

目前我正在使用 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

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

提前致谢!

您好。

【问题讨论】:

    标签: c# .net list collections outlook


    【解决方案1】:

    我能够使用 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; }
       }
    }
    

    【讨论】:

      【解决方案2】:

      不要使用从 1 到 myAppointmentItems 的“for”循环来使用“foreach”循环。不要忘记对其进行排序 (myAppointmentItems.Sort(...)) 以获得有意义的顺序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 2021-08-24
        相关资源
        最近更新 更多