-3

I want to compare elements inside a single List in C#. I need to check whether same data is there in list or not . Can anybody help me with this?

EgoPingvina
  • 734
  • 1
  • 10
  • 33
ayushi dixit
  • 27
  • 1
  • 6

3 Answers3

0

You can try this, for example:

var collection = new List<double>(new double[] { 10, 20, 11, 10, 20, 44 });
var info = collection.GroupBy(e => e).ToDictionary(e => e.Key, e => e.Count());

Here info contain a double value as a key and number of this number in collection as value.

And this construction you can use with any type of List elements.

EgoPingvina
  • 734
  • 1
  • 10
  • 33
-1

You could use the LINQ extention methods

here is an example of LINQ comparing lists:

   list<string>  arr1 = new list<string>(){ "A", "b", "C," };
   list<string>  arr2 = new list<string>(){ "A", "b", "C," };

Compare the above arrays with the SequentialEqual() Method

bool result = arr3.SequentialEqual(arr2);

The Boolean result will contain true as the items in both lists are equal

Hope this helps

LH NCL
  • 34
  • 2
-1

If you just want to know if there is more than one item in the list has the same value you can use this function..

public bool HasSameData<T>(List<T> myList)
{
    return myList.Distinct().Count() != myList.Count();
}

note that this will work with any type.

void Main()
{
    var myList = new List<int> {1,2,3,4,5,6,7,8,9};
    var myList2 = new List<int> {1,1,3,4,5,6,7,8,9};

    Console.WriteLine(HasSameData(myList));
    Console.WriteLine(HasSameData(myList2));

    var myList3 = new List<String> {"hello","world","foo","bar"};
    var myList4 = new List<String> {"hello","foo","foo","bar"};

    Console.WriteLine(HasSameData(myList3));
    Console.WriteLine(HasSameData(myList4));

    Console.ReadLine();
}

OUTPUT:

False
True
False
True
Callback Kid
  • 708
  • 5
  • 22