You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中向DataGrid添加数据报错:无法对IEnumerable使用索引

问题解决:HashSet无法通过索引访问的错误修复

错误原因

HashSet<T> 本身不支持**索引器([])**访问,它仅实现了IEnumerable<T>接口,没有提供按下标获取元素的能力,所以你用Alert.alerts[i]的写法会触发报错。

修复方案

方法1:用foreach遍历HashSet

直接遍历Alert.alerts集合,将元素逐个添加到ObservableCollection中:

public AdminWindow()
{
    InitializeComponent();

    ObservableCollection<Alert> alertToDataGrid = new ObservableCollection<Alert>();
           
    foreach (var alert in Alert.alerts)
    {
        alertToDataGrid.Add(alert);
    }

    AlertTable.ItemsSource = alertToDataGrid;
}

方法2:直接利用ObservableCollection构造函数(更简洁)

ObservableCollection的构造函数支持直接传入IEnumerable<T>类型的集合,所以可以一步完成转换:

public AdminWindow()
{
    InitializeComponent();

    ObservableCollection<Alert> alertToDataGrid = new ObservableCollection<Alert>(Alert.alerts);
    AlertTable.ItemsSource = alertToDataGrid;
}

额外优化建议

  1. 移除不必要的IEnumerable实现:你的Alert类是单个告警实体,不需要实现IEnumerable<Alert>接口——静态字段alerts本身就是可枚举的集合,当前实现会造成语义混淆,直接删除以下代码即可:
public IEnumerator<Alert> GetEnumerator()
{
    foreach (Alert alert in alerts)
    {
        yield return alert;
    }
}

IEnumerator IEnumerable.GetEnumerator()
{
    return this.GetEnumerator();
}
  1. 修正Equals和GetHashCode冗余逻辑:方法中重复比较了id字段和Id属性(二者是封装关系),简化为:
public override bool Equals(object obj)
{
    return obj is Alert alert && id == alert.id;
}

public override int GetHashCode()
{
    return HashCode.Combine(id);
}

内容的提问来源于stack exchange,提问作者Tvaruzek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 01:15:41