<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>FailBoy &#187; Linq</title>
	<atom:link href="http://www.failboy.net/tag/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.failboy.net</link>
	<description>We reserve the right FAIL</description>
	<lastBuildDate>Thu, 26 Nov 2009 06:29:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>LINQ: Distinct method</title>
		<link>http://www.failboy.net/2009/07/linq-distinct-method/</link>
		<comments>http://www.failboy.net/2009/07/linq-distinct-method/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 19:44:14 +0000</pubDate>
		<dc:creator>FailBoy</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Distinct]]></category>
		<category><![CDATA[IEnumerable]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.failboy.net/?p=42</guid>
		<description><![CDATA[Ah the beauty of LINQ. I previously did a post on How to use Lambda Expressions and if you aren&#8217;t sure now how to use them, is the time to check it out. I have decided to have a good look at the Methods available to IEnumerable collections and first on the list the DISTINCT [...]]]></description>
			<content:encoded><![CDATA[<p>Ah the beauty of LINQ. I previously did a post on<a title="how to use lambda expressions" href="http://www.failboy.net/2009/07/how-to-use-lambda-expressions/" target="_blank"> How to use Lambda Expressions</a> and if you aren&#8217;t sure now how to use them, is the time to check it out. I have decided to have a good look at the Methods available to IEnumerable collections and first on the list the DISTINCT method.</p>
<p><span style="text-decoration: underline;"><strong>The Boring Standard Method:</strong></span></p>
<p>The Distinct method removes any duplicate entries in a collection without you needing to do much work, the same as the DISTINCT keyword inT-SQL. Here is the basic and standard use that is really not difficult to understand.</p>
<pre class="brush: csharp;">
string[] names = new string[] { &quot;Peter&quot;, &quot;Paul&quot;, &quot;Mary&quot;, &quot;Peter&quot;, &quot;Paul&quot;, &quot;Mary&quot;, &quot;Janet&quot; };

foreach (string _name in names.Distinct())
{
Console.WriteLine(_name);
}</pre>
<p>So like I said, easy enough, we have a string array with names and by using the .Distinct method we remove any duplicates from the resultset that is returned. Now comes the real fun!</p>
<p><span style="text-decoration: underline;"><strong>Custom Distinct Implementation:</strong></span></p>
<p>Since the advent of generics, most of us have been creating strongly typed lists of data. Plain example would be a list of our customer UserClass.</p>
<pre class="brush: csharp;">
public class Users
{
public int ID {get; set;}
public string Name {get; set;}
public int AwesomeScore {get; set;}
}

// Create and populate new list of Users
List&lt;Users&gt; failBoyUsers = new List&lt;Users&gt;();
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = &quot;FailBoy&quot;, ID = 1 });
failBoyUsers.Add(new Users { AwesomeScore = 10, Name = &quot;Rathlan&quot;, ID = 2 });
failBoyUsers.Add(new Users { AwesomeScore = 10, Name = &quot;Rathlan&quot;, ID = 2 });
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = &quot;Joe&quot;, ID = 3 });
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = &quot;Joe&quot;, ID = 3 });
failBoyUsers.Add(new Users { AwesomeScore = 7, Name = &quot;Joe&quot;, ID = 3 });
failBoyUsers.Add(new Users { AwesomeScore = 1, Name = &quot;newbie&quot;, ID = 4 });
</pre>
<p>This would then give us a &#8220;strongly typed Array&#8221; of our User class. If we now had to call the .Distinct function on the collection it wouldn&#8217;t work! Thats because the CLR does not know what to evaluate to decide whether an entry is unique or a duplicate so it returns all the items including the duplicates. The Distinct method accepts an overload paramter, this object must implement the IEqualityComparer interface. So we declare a new class and implement IEqualityComparer as follows:</p>
<pre class="brush: csharp;">
public class AwesomeComparer : IEqualityComparer&lt;Users&gt;
{
public bool Equals(Users x, Users y)
{
if (x == null || y == null)
return false;
else
return (x.Name.ToLower() == y.Name.ToLower() &amp;&amp;
x.AwesomeScore == y.AwesomeScore &amp;&amp;
x.ID == y.ID);
}

public int GetHashCode(Users obj)
{
return obj.Name.GetHashCode();
}
}
</pre>
<p>so what we do in the Equals Method is define what we feel a duplicate of our custom class looks like. We also implement the GetHashCode method to return the hash of the &#8220;primary field&#8221;. This will usually be the Primary Key that you class will be based on. Then we implement our Distinct method, we do so as follows:</p>
<pre class="brush: csharp;">
AwesomeComparer awesomeComparer = new AwesomeComparer();

foreach (Users usr in failBoyUsers.Distinct(awesomeComparer))
{
Console.WriteLine(usr.ID.ToString() + &quot; - &quot; + usr.Name + &quot; - &quot; + usr.AwesomeScore.ToString());
}
</pre>
<p>And that will only return Distinct values from our custom class! I hope this helps someone at some stage as I never knew about this myself and stumbled onto it. Drop me a comment if you think I suck or if my some margain of luck I managed to produce some bug free code, I am after FailBoy for a reason <img src='http://www.failboy.net/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.failboy.net/2009/07/linq-distinct-method/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Convert LiNQ resultset to DataTable</title>
		<link>http://www.failboy.net/2009/05/convert-linq-resultset-to-datatable/</link>
		<comments>http://www.failboy.net/2009/05/convert-linq-resultset-to-datatable/#comments</comments>
		<pubDate>Wed, 06 May 2009 12:22:27 +0000</pubDate>
		<dc:creator>FailBoy</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[DataTable]]></category>
		<category><![CDATA[ExtensionMethod]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.failboy.net/?p=5</guid>
		<description><![CDATA[When the LiNQ to SQL framework was originally released in BETA there was a built in extension method to convert the LiNQ result to either a DataTable or DataSet if I remember correctly. However when it came to release this disappeared for some strange reason. Now I&#8217;m sure MS had their reasons for removing it [...]]]></description>
			<content:encoded><![CDATA[<p>When the LiNQ to SQL framework was originally released in BETA there was a built in extension method to convert the LiNQ result to either a DataTable or DataSet if I remember correctly. However when it came to release this disappeared for some strange reason.</p>
<p>Now I&#8217;m sure MS had their reasons for removing it but I don&#8217;t care and want it back <img src='http://www.failboy.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  So I&#8217;ve written a little extension method to convert the LiNQ resultset to a DataTable using a bit of Reflection. Here&#8217;s the code and enjoy! As always, I take no responsibility for its usage <img src='http://www.failboy.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<blockquote><p>/// &lt;summary&gt;<br />
/// Converts an IEnumerable type collection into a DataTable<br />
/// &lt;/summary&gt;<br />
/// &lt;param name=&#8221;collection&#8221;&gt;Collection type that implements IEnumberable&lt;/param&gt;<br />
/// &lt;returns&gt;Datatable representing IEnumerable collection&lt;/returns&gt;<br />
public static DataTable ToDataTable&lt;T&gt;(this IEnumerable&lt;T&gt;collection)<br />
{<br />
// Create DataTable to Fill<br />
DataTable _newDataTable = new DataTable();</p>
<p>// Retrieve the Type passed into the Method<br />
Type _impliedType = typeof(T);</p>
<p>//Get an array of the Type&#8217;s properties<br />
PropertyInfo[] _propInfo = _impliedType.GetProperties();</p>
<p>//Create the columns in the DataTable<br />
foreach (PropertyInfo pi in _propInfo)<br />
{<br />
_newDataTable.Columns.Add(pi.Name, pi.PropertyType);<br />
}</p>
<p>//Populate the table<br />
foreach (T item in collection)<br />
{<br />
DataRow _newDataRow = _newDataTable.NewRow();<br />
_newDataRow.BeginEdit();</p>
<p>foreach (PropertyInfo pi in _propInfo)<br />
{<br />
_newDataRow[pi.Name] = pi.GetValue(item, null);<br />
}</p>
<p>_newDataRow.EndEdit();<br />
_newDataTable.Rows.Add(_newDataRow);<br />
}</p>
<p>return _newDataTable;<br />
}</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.failboy.net/2009/05/convert-linq-resultset-to-datatable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
