如何从ICollection中检索类对象?

时间:2014-06-25 14:11:44

标签: c# asp.net linq

我有2个课程UsersUserdetails

User包含Userdetails ICollection;

public class Users
{
    public int Id;
    public ICollection<Userdetails> Userdetails;
}

我想从UserDetails对象中检索User对象但找不到方法;

我已经用这种方式实现了它:

var  lstUserdetails = new List<Userdetails>();
lstUserdetails = (from e in user.Userdetails
                      select e).ToList();
var userobject = ((Userdetails)lstUserdetails.Find(x=>x.id == Id));

但它显示userobject null。

如何解决?

2 个答案:

答案 0 :(得分:0)

var userDetailsObejct = (from u in user.UserDetails 
                         where u.id == Id
                         select u).FirstOrDefault();

这将从具有等于Id的id的指定用户返回UserDetails集合中的UserDetails对象。如果找不到它,它将返回null。

答案 1 :(得分:-1)

试试这个

var  lstUserdetails = new List<Userdetails>();
lstUserdetails = (from e in user.Userdetails where e.id == Id 
                  select e).Firstordefault();