how to check if object already exists in a list

前端 未结 9 1794
梦谈多话
梦谈多话 2020-11-28 05:41

I have a list

  List myList

and I am adding items to a list and I want to check if that object is already in the list.

9条回答
  •  借酒劲吻你
    2020-11-28 05:45

    Here is a quick console app to depict the concept of how to solve your issue.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication3
    {
        public class myobj
        {
            private string a = string.Empty;
            private string b = string.Empty;
    
            public myobj(string a, string b)
            {
                this.a = a;
                this.b = b;
            }
    
            public string A
            {
                get
                {
                    return a;
                }
            }
    
            public string B
            {
                get
                {
                    return b;
                }
            }
        }
    
    
        class Program
        {
            static void Main(string[] args)
            {
                List list = new List();
                myobj[] objects = { new myobj("a", "b"), new myobj("c", "d"), new myobj("a", "b") };
    
    
                for (int i = 0; i < objects.Length; i++)
                {
                    if (!list.Exists((delegate(myobj x) { return (string.Equals(x.A, objects[i].A) && string.Equals(x.B, objects[i].B)) ? true : false; })))
                    {
                        list.Add(objects[i]);
                    }
                }
            }
        }
    }
    

    Enjoy!

提交回复
热议问题