在readOnlyCollection中使用linq的where子句

时间:2013-05-27 10:09:27

标签: c# linq

我有一个ModuleViewModel的readOnlyCollection,我想用linq检索包含在我的集合中的特定ModuleViewModel。

这里是我的收藏宣言:

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;

我想检索其中Id == idMod

的ModuleViewModel
  

对象obj =来自colModuleViewModel中的c在哪里?选择c;

2 个答案:

答案 0 :(得分: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. 查询语法在这种情况下没有用处,您最好使用方法链语法:

    object obj = colModuleViewModel.FirstOrDefault(x => x.Id == idMod);
    

答案 1 :(得分:1)

object obj = (from c in colModuleViewModel where c.Module.Id == Id select c).FirstOrDefault();