ObservableCollection<T>获取索引

如果是普通类型我们直接可以用indexOf()获取,比如:

ObservableCollection<string> oc = new ObservableCollection<string>();
oc.Add("Item1");
oc.Add("Item2");
oc.Add("Item3");
 
string item = "Item2";
int index = oc.IndexOf(item);
Console.WriteLine(index); // 输出:1

但如果是自定义的类型,切内部存在多个成员时,我们要根据某一成员获取这成员所在行的所以值就无法这样用了

自定义类型:

public class ConnectDataModel: NotifyBase
    {
        private string _num;
        public string Num
        {
            get { return _num; }
            set { _num = value; this.NotifyChanged(); }
        }

        private string _tagName;
        public string TagName
        {
            get { return _tagName; }
            set { _tagName = value; this.NotifyChanged(); }
        }


        private string _description;
        public string Description
        {
            get { return _description; }
            set { _description = value; this.NotifyChanged(); }
        }


        private string _dataType;
        public string DataType
        {
            get { return _dataType; }
            set { _dataType = value; this.NotifyChanged(); }
        }

        private string _adress;
        public string Adress
        {
            get { return _adress; }
            set { _adress = value; this.NotifyChanged(); }
        }


        private string _driver;
        public string Driver
        {
            get { return _driver; }
            set { _driver = value; this.NotifyChanged(); }
        }

        private string _value;
        public string Value
        {
            get { return _value; }
            set { _value = value; this.NotifyChanged(); }
        }

定义集合:

public static ObservableCollection<ConnectDataModel> ConnectDataCollection { get; set; } = new ObservableCollection<ConnectDataModel>();

为集合添加数据:

                                ConnectDataCollection.Add(new ConnectDataModel {
                                    //Num ="1",
                                    TagName= "AA",
                                    Description= "BB",
                                    DataType= "CC",
                                    Adress= "DD",
                                    Driver= "EE"

                                });

我们通过"AA"来获取其所在的索引

ConnectDataModel TagNameCollection = ConnectViewModel.ConnectDataCollection.Where(o => o.TagName == "AA").SingleOrDefault();////Linq获取列表选中值(唯一元素)
                                    int index = ConnectViewModel.ConnectDataCollection.IndexOf(TagNameCollection);//获取列表选中值的索引
                                    ConnectViewModel.ConnectDataCollection.RemoveAt(index);//移除

 

posted @ 2024-10-30 21:09  灰色小五  阅读(3)  评论(0编辑  收藏  举报