【问题标题】:C#: alternative to exists or getfirstordefaultC#:exists 或 getfirstordefault 的替代方案
【发布时间】:2013-10-22 13:30:39
【问题描述】:

我有课

class Person {

 int Age;
 string Name;
}

List<Person> pList = new List<Person>();

 pList.Exists(p=> p.Name == "testName");  <-- need an alternative for this.

我正在使用 .net 3.0。

因此我无权使用getFirstOrDefault 方法。

Exists 方法为空值抛出异常,但我不想中断我的程序流程;还有其他选择吗?

我也没有 AnyLinq 可用。

【问题讨论】:

  • 你有什么?你有数组、列表、IEnumerable 还是什么?那个系列里面有什么?你想用那个集合做什么?显示一些示例输入/输出。

标签: c# collections .net-3.0


【解决方案1】:

Exists 应该没问题 - 你只需要处理p 成为null 的可能性。

bool nameExists = pList.Exists(p => p != null && p.Name == "testName");

或者,请确保您的列表不包含任何 null 引用开头 - 这可能会让您更轻松地完成各种事情。

【讨论】:

    【解决方案2】:
    bool nameExists = pList.Any(p=>p.Name == "testName");
    

    或者(如果你不使用Any):

    bool nameExists = pList.Select(p=>p.Name).Contains("testName");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多