How to get all items from a list that are not unique with LINQ

If you want to get all items from a list that are not unique with LINQ and C#, you can use:

public static void CountItemsPerCategoryButNotUnique()
        {
            List<string> items = new List<string>();
            items.Add("Item 1");
            items.Add("Item 2");
            items.Add("Item 3");
            items.Add("Item 4");
            items.Add("Item 2");
            items.Add("Item 3");

            var result = from i in items
                         group i by i into g
                         where g.Count() > 1
                         select new { Group = g.Key, ItemCount = g.Count() };

            foreach (var test in result)
            {
                Console.WriteLine(string.Format("Group [ {0} ] ItemCount [ {1} ]", test.Group, test.ItemCount));
            }

        }
Output

How to get all items from a list that are not unique with LINQ How to get all items from a list that are not unique with LINQ Reviewed by Bhaumik Patel on 1:12 AM Rating: 5