Remove duplicate objects in list in C#


Just sharing a sample code to remove duplicates from a list using linq

</p>
<p>public class MyClass<br />
{<br />
public string ID { get; set; }<br />
public string Value { get; set; }</p>
<p>}</p>
<p>List&lt;MyClass&gt; myList = new List&lt;MyClass&gt;();<br />
var xrmOptionSet = new MyClass();<br />
xrmOptionSet.ID = "1";<br />
xrmOptionSet.Value = "100";<br />
var xrmOptionSet1 = new MyClass();<br />
xrmOptionSet1.ID = "2";<br />
xrmOptionSet1.Value = "200";<br />
var xrmOptionSet2 = new MyClass();<br />
xrmOptionSet2.ID = "1";<br />
xrmOptionSet2.Value = "100";<br />
myList.Add(xrmOptionSet);<br />
myList.Add(xrmOptionSet1);<br />
myList.Add(xrmOptionSet2);</p>
<p>// here we are first grouping the result by label and then picking the first item from each group<br />
var myDistinctList = myList.GroupBy(i =&gt; i.ID)<br />
.Select(g =&gt; g.First()).ToList();</p>
<p>

Hope it helps..

Load your programming emulators on the cloud & access it conveniently on virtual desktops with your preferred mobile device (iOS/Android/windows) remotely with CloudDesktopOnline.com. For effective team collaboration use a hosted SharePoint and exchange from Apps4Rent.

Advertisements

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

15 thoughts on “Remove duplicate objects in list in C#”

Leave a Reply to Anonymous Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.