2013-05-27 44 views
2

我有一個ReadOnlyCollection ModuleViewModel,我想用linq檢索包含在我的集合中的特定ModuleViewModel。在子句中的linq在readOnlyCollection中的對象

這裏我收藏的聲明:

public ReadOnlyCollection<ModuleViewModel> colModuleViewModel { get; set; } 

colModuleViewModel = new ReadOnlyCollection<ModuleViewModel>(
       (from mod in currentProg.Tests.Values 
       select new ModuleViewModel(mod)) 
      .ToList<ModuleViewModel>()); 

我ModuleViewModel類:

public class ModuleViewModel : INotifyPropertyChanged 
    { 
     readonly ReadOnlyCollection<ModuleViewModel> _children; 
     readonly ModuleViewModel _parent; 
     readonly Module _module; 

     public ReadOnlyCollection<ModuleViewModel> Children 
     { 
      get { return _children; } 
     } 

     bool _isExpanded; 
     bool _isSelected; 

     public ModuleViewModel(Module module) 
      : this(module, null) 
     { 

     } 

     private ModuleViewModel(Module module, ModuleViewModel parent) 
     { 
      _module = module; 
      _parent = parent; 

      if (module is Task) 
      { 
       _children = new ReadOnlyCollection<ModuleViewModel>(
        (from mod in ((Task)module).Tests.Values 
        select new ModuleViewModel(mod, this)) 
       .ToList<ModuleViewModel>()); 
      } 
      else 
      { 
       _children = null; 
      } 
     } 

     public ModuleViewModel Parent 
     { 
      get { return _parent; } 
     } 

     public string Name 
     { 
      get { return _module.Name; } 
     } 

     public string Id 
     { 
      get { return (_module is Test ? ((Test)_module).Id : ((Task)_module).Id); } 
     } 
    } 

我有ModuleViewModel的Id:

string idMod = ((Module)currentProgram.finalDico[data.ToString()]).Id; 

我要檢索的ModuleViewModel其中Id == idMod

object obj = from c in colModuleViewModel where ?? ??選擇c;

回答

5
  1. WHERE條件很簡單:c.Id == idMod

    from c in colModuleViewModel where c.Id == idMod select c 
    
  2. 當你只想要一個單一的對象,而不是對象的集合,你必須使用FirstOrDefault()

    (from c in colModuleViewModel where c.Id == idMod select c).FirstOrDefault(); 
    
  3. 查詢語法在這種情況下不是有利的,您最好使用方法c語法漢斯:

    object obj = colModuleViewModel.FirstOrDefault(x => x.Id == idMod); 
    
1
object obj = (from c in colModuleViewModel where c.Module.Id == Id select c).FirstOrDefault(); 
+0

你應該重新格式化的回答聽起來不是什麼問題。 –