Linq返回对象列表部分中的单个项目

时间:2014-03-20 06:28:46

标签: c# linq

我有以下数据库表:

# account_type table #

id       desc
----------------
1        savings
2        checking 

# account table #

id  account_type_id   Name
--------------------------
1       2             Don
2       1             Henry
3       1             Lisa
4       2             Jenifer 

我想写一个linq查询,以便它返回带有集合的对象,即

desc: Savings { Don, Jenifer }

我创建了这些类:

public class acctType
{
    public id { get; set; }
    public string desc { get; set; }
    public IEnumerable<account> account{ get; set;}
}

public class account
{
    public int id { get; set; }
    public int account_type_id { get; set; }
    public string name { get; set;}
}

我在api中的方法是调用:

public accType Get(int id)
{
    var accounts = (from c in db.account_type
                    where c.p_id == id
                    select new accType
                    {
                        id = c.id,
                        name = c.desc,
                        account = new List<account> { name = c.desc }
                    });
  }
  return accounts.FirstOrDefault()

问题是,当我收到帐户对象时,它只有一个名称,即

dsc: checking { Don }

虽然答案应该是Don和Jenifer。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您只返回FirstOrDefault()项,将return语句更改为

return accounts.ToList()

编辑:

public List<accType> Get(int id)
{
  var accounts = (from c in db.account_type
                        where c.p_id == id
                        select new accType
                        {
                            id = c.id,
                            name = c.desc,
                            account = new List<account>()
                            {
                               name=c.desc
                            }
                        });
   return accounts.ToList()
}