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

如何在Xamarin Forms(C#)中向ListView添加不重复的值

解决Xamarin Forms ListView添加不重复数据的方法

方法一:添加数据前检查重复

在向集合中添加新数据前,先判断该数据是否已存在(以IntRow作为唯一标识,可根据实际业务调整),避免重复插入:

// 创建新数据项
var newInventoryItem = new InventoryPerRow 
{ 
    IntRow = Convert.ToInt32(Row.Text), 
    IntPlants = Convert.ToInt32(TotalPlants.Text), 
    IntPlantsUnusable = Convert.ToInt32(PlantsUnusable.Text) 
};

// 检查集合中是否已有相同IntRow的项
if (!InventoryPerRowModel.Any(item => item.IntRow == newInventoryItem.IntRow))
{
    InventoryPerRowModel.Add(newInventoryItem);
    // 重新排序并绑定数据源
    var sortedUniqueData = InventoryPerRowModel.OrderBy(x => x.IntRow).ToList();
    MyListView.ItemsSource = sortedUniqueData;
}

方法二:对现有集合去重

如果已经存在重复数据,可通过以下方式批量去重后再绑定:

方式1:实现相等比较接口

给InventoryPerRow类实现IEquatable<T>接口,明确重复判断规则:

public class InventoryPerRow : IEquatable<InventoryPerRow>
{
    public int IntRow { get; set; }
    public int IntPlants { get; set; }
    public int IntPlantsUnusable { get; set; }

    public bool Equals(InventoryPerRow other)
    {
        if (other == null) return false;
        return IntRow == other.IntRow; // 以IntRow作为重复判断依据
    }

    public override bool Equals(object obj) => Equals(obj as InventoryPerRow);
    public override int GetHashCode() => IntRow.GetHashCode();
}

之后调用Distinct()方法去重并排序:

var sortedUniqueData = InventoryPerRowModel.Distinct()
                                           .OrderBy(x => x.IntRow)
                                           .ToList();
MyListView.ItemsSource = sortedUniqueData;

方式2:使用DistinctBy(简便写法)

如果项目基于.NET Core 3.0+或引入了System.Linq.Dynamic.Core包,可直接用DistinctBy指定去重字段:

var sortedUniqueData = InventoryPerRowModel.DistinctBy(x => x.IntRow)
                                           .OrderBy(x => x.IntRow)
                                           .ToList();
MyListView.ItemsSource = sortedUniqueData;

注意事项

  • 确保用于判断唯一性的字段(如IntRow)符合业务场景的唯一标识要求,避免误过滤有效数据。
  • 若使用ObservableCollection作为数据源,添加数据时会自动触发UI更新;若使用普通List,每次修改后需重新绑定数据源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:50:49