如何检查收集是否有任何物品?我的示例是 IEnumerable 的类型,标准的LINQ方法(例如.Any()、. Count()、. ToList()等)不起作用。
据我测试,几乎所有的LINQ方法都抛出异常。奇怪的是,测试对象不是null(将该对象比较为null则返回false)
当我比较null时:
更新
负责此收藏的代码:
var secondLevelsSubGroups = _treeBranches.SubGroup.Where(w => w.Parent.GetType() == item.GetType() && w.Parent.Name == item.Name);
if (!IsNull(secondLevelsSubGroups))
如果collection不为空,则可以通过Foreach循环进行迭代。
集合中的每个项目都包含一个称为“父对象”的属性。该对象可以是4种不同类型的对象之一
更新2
与此情况有关的所有代码:
public class GroupedTreeBranches
{
public IEnumerable<SubGroup> SubGroup { get; set; }
}
public class SubGroup : TreeNode
{
public int ID { get; set; }
public int SubGroupParent { get; set; }
public decimal DefaultValue { get; set; }
private bool _isCheckedInMenu;
public bool IsCheckedInMenu
{
get { return _isCheckedInMenu; }
set
{
_isCheckedInMenu = value;
OnPropertyChanged("IsCheckedInMenu");
}
}
private bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
_isExpanded = value;
if (_isExpanded == true)
{
Rotations = new ObservableCollection<Rotation>(new RotationLogicService().GetAllPositions(ID));
if (IsCheckedInMenu)
{
foreach (var rotation in Rotations)
{
rotation.IsCheckedInMenu = true;
}
}
}
else
{
//Rotations.Add(new Rotation()); // dummy child to keep expander icon visible
}
OnPropertyChanged("IsExpanded");
}
}
private ObservableCollection<Rotation> rotations = new ObservableCollection<Rotation>();
public ObservableCollection<Rotation> Rotations
{
get { return rotations; }
set
{
rotations = value;
OnPropertyChanged("Rotations");
}
}
}
public class TreeNode : ViewModelBase, ITreeNode
{
public ObservableCollection<ITreeNode> Children { get; set; }
public string Name { get; set; }
public ITreeNode Parent { get; set; }
public TreeNode()
{
Children = new ObservableCollection<ITreeNode>();
}
public void AddChild(ITreeNode child)
{
Children.Add(child);
}
public void RemoveChild(ITreeNode child)
{
Children.Remove(child);
}
}
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
}
}
在我的课堂上,我创建了:
private GroupedTreeBranches _treeBranches;
接下来,它由我从数据库获得的数据填充,然后由WHERE函数使用:
var secondLevelsSubGroups = _treeBranches.SubGroup.Where(w => w.Parent.GetType() == item.GetType() && w.Parent.Name == item.Name);
最终
正如@Rup所建议的,以及当我更改订单顺序时,我再次检查了带有附加WHERE子句的解决方案(为null)
var secondLevelsSubGroups = _treeBranches.SubGroup.Where(w => w.Parent.GetType() == item.GetType() && w.Parent.Name == item.Name && w.Parent != null);
进入
var secondLevelsSubGroups = _treeBranches.SubGroup.Where(w => w.Parent != null && w.Parent.GetType() == item.GetType() && w.Parent.Name == item.Name);
它开始工作。谢谢大家的帮助
ps。有谁知道为什么它不能更早地起作用?