如何在linq中使用select to string?

时间:2010-06-25 10:24:41

标签: c# .net visual-studio-2008 linq

我如何使用下面的代码字符串id =(来自.....)怎么样?

using (StockProcedureDataContext stock = new StockProcedureDataContext())
            {


                id = (from m in stock.StockTools
                      from ss in stock.RefStockStatus
                      where (m.statusid == 3 || m.statusid == 5) &&
                      ss.id == m.statusid && m.id == ItemID
                      select m.id);

如何在不使用下方的情况下进行上述操作?

id = (from m in stock.StockTools
                      from ss in stock.RefStockStatus
                      where (m.statusid == 3 || m.statusid == 5) &&
                      ss.id == m.statusid && m.id == ItemID
                      select m).ToList()[0].id;

4 个答案:

答案 0 :(得分:4)

query.Single()   

就是这样。

答案 1 :(得分:4)

id = (from m in stock.StockTools
                      from ss in stock.RefStockStatus
                      where (m.statusid == 3 || m.statusid == 5) &&
                      ss.id == m.statusid && m.id == ItemID
                      select m.id).FirstOrDefault();

答案 2 :(得分:2)

如果您想要检索单个结果用户FirstOrDefault()First()

如果您使用First()且结果为null。它将抛出异常,但不会抛出FirstOrDefault()

var query = (from m in stock.StockTools
                      from ss in stock.RefStockStatus
                      where (m.statusid == 3 || m.statusid == 5) &&
                      ss.id == m.statusid && m.id == ItemID
                      select m.id).FirstOrDefault();

答案 3 :(得分:1)

只是为了变化...

query.Take(1)