19 January, 2010
0 Comments
0 categories
If you want to get all items from a list that are not unique with LINQ and C#, you can use:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; namespace Ada.Cdf.Test { [TestFixture] public class IntegrationTester { [Test] [Explicit("Not a unittest")] public void Test() { 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)); } } } }
Result
Group[Item 2] ItemCount[2]
Group[Item 3] ItemCount[2]