using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<User> Users = new List<User>();
User user = Users.First();
if (user != null)
Console.WriteLine(user.Name);
Console.ReadKey();
}
}
}程序执行出错:

原因是Users集合内没有任何元素,它是一个空集合,调用First方法所以提示序列不包含任何元素,这和调用null对象属性报错提示未将对象引用设置到对象的实例是一个道理。
Linq序列不包含任何元素解决方法
将First方法改为FirstOrDefault即可:
User user = Users.FirstOrDefault();
评论(0)
暂无评论。