读取列表<custom class =“”>包含单个记录</custom>

时间:2012-12-05 11:31:50

标签: c# linq collections

我有一个列表,其中有一条记录,即与特定ID匹配。

现在我想使用此列表的属性( 即该单个记录的列 )而不使用FOREACH循环,因为它只会给服务器带来负担,因为我的程序是已经有很多循环...... 可以吗?

我正在根据ID过滤从ViewState带来的记录。

var selectedPracticeInfo = 
          (List<PropPractice>) ViewState["dicPracticesInGrupWithTimeZone"];

var selectedPracticeforEncounter = 
             from selectedPractice in selectedPracticeInfo
             where 
                selectedPractice.PracticeId 
                     == Convert.ToInt32(ddlPractice.SelectedValue)
  select new PropPractice
  {
    PracticeId = selectedPractice.PracticeId,
    PracticeName = selectedPractice.PracticeName,
    TimeZoneDisplayName = selectedPractice.TimeZoneDisplayName
  };

我打算做类似这样的事情,它会直接取出那条Single记录的TimeZoneDisplayName,但它说“字符串不能用作布尔值”..

var practiceTimeZoneName 
       = selectedPracticeforEncounter
               .Single(practice=>practice.TimeZoneDisplayName

所以,我想询问是否可以通过某种方式完成,除了 FOREACH ??

3 个答案:

答案 0 :(得分:1)

var practiceTimeZoneName=selectedPracticeforEncounter.Single().TimeZoneDisplayName

答案 1 :(得分:1)

这是否符合您的要求? First或Default将确保您获得单个记录或null

var result = selectedPracticeInfo
             .Where(m=> m.PracticeID == (Int32)ddlPractice.SelectedValue)
             .FirstOrDefault();

if(result != null){

var timezone = result.TimeZoneDisplayName;

}

结果将是一种PropPractice,但是对于良好实践,可以使用强烈定义的

PropPractice = selectedPracticeInfo
               .Where(m=> m.PracticeID == (Int32)ddlPractice.SelectedValue)
               .FirstOrDefault();

您不需要以下内容来创建新对象:

select new PropPractice
  {
    PracticeId = selectedPractice.PracticeId,
    PracticeName = selectedPractice.PracticeName,
    TimeZoneDisplayName = selectedPractice.TimeZoneDisplayName
  };

答案 2 :(得分:1)

如果您只想要一个,那么尝试将.SingleOrDefualt添加到LINQ查询的末尾

var selectedPracticeforEncounter = (from selectedPractice in selectedPracticeInfo
                                         where selectedPractice.PracticeId == Convert.ToInt32(ddlPractice.SelectedValue)
 select new PropPractice
{
PracticeId = selectedPractice.PracticeId,
PracticeName = selectedPractice.PracticeName,
TimeZoneDisplayName = selectedPractice.TimeZoneDisplayName
}).SingleOrDefault();

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria