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?
Asked
Active
Viewed 6,324 times
-3

EgoPingvina
- 734
- 1
- 10
- 33

ayushi dixit
- 27
- 1
- 6
-
1Anything tried so far? – Tim Schmelter Dec 09 '16 at 11:32
-
2`bool contains = list.Any(item => condition(item));` – Dmitry Bychenko Dec 09 '16 at 11:33
-
Are you wanting to get a report as to whether there are duplicate items, or clear out duplicates? http://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property – ColinM Dec 09 '16 at 11:46
3 Answers
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