Introduction
In this article, we will discuss about unique array items in C# using a traditional approach, LINQ, and non-case sensitive unique array items in LINQ.
Traditional Approach
Unique array items can be displayed by using for loop and checking the existence of duplicate items in the array. Here is the code to display unique array items using a traditional approach. Let’s take array 2, 3, 5, 3, 7, 5.
- static void Main(string[] args)
- {
- int[] items = { 2, 3, 5, 3, 7, 5 };
- int n = items.Length;
-
- Console.WriteLine("Unique array elements: ");
-
- for(int i=0; i<n;i++)
- {
- bool isDuplicate = false;
- for(int j=0;j<i;j++)
- {
- if(items[i] == items[j])
- {
- isDuplicate = true;
- break;
- }
- }
-
- if(!isDuplicate)
- {
- Console.WriteLine(items[i]);
-
- }
- }
-
- Console.ReadLine();
- }
Output
LINQ Approach
To use LINQ import namespace System.Linq. There is a Distinct() method in Linq which gives unique items.
- static void Main(string[] args)
- {
- int[] items = { 2, 3, 5, 3, 7, 5 };
- IEnumerable<int> uniqueItems = items.Distinct<int>();
- Console.WriteLine("Unique array elements using LINQ: " + string.Join(",", uniqueItems));
-
- Console.ReadLine();
- }
Output
Unique array items without case sensitive using LINQ in C#
In SQL if we have to get unique items, distinct keyword gives unique non case sensitive items because SQL is not a case sensitive language. So it’s not as easy to use in LINQ because C# is a case sensitive language. Let’s take a list of array items: AAA, Bbb, Aaa, bbb, CCC, Ddd, aaa, CCC. There are 8 items here, out output should be like Aaa, Bbb, Ccc, Ddd.
To display items in title case we need to use TextInfo class. In order to use textInfo class import System.Globalization class.
- class Program
- {
- static void Main(string[] args)
- {
- string[] items = { "AAA", "Bbb", "Aaa", "bbb", "CCC", "Ddd", "aaa", "CCC" };
-
- IEnumerable<string> uniqueItems = items.Select(x => x.ToLower()).Distinct<string>();
- TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
- uniqueItems = uniqueItems.Select(x => textInfo.ToTitleCase(x));
- Console.WriteLine("Unique array elements using LINQ without case sensitive: " + string.Join(",", uniqueItems));
-
- Console.ReadLine();
- }
- }
Output
Conclusion
In this blog, we got unique array items using For loop and LINQ. Also, we displayed non-case sensitive items using LINQ and TextInfo class.