LINQ LIST: Distinct method extension

While operating with collections, sometime we would like to perform Distinct on column, to achieve this we need to write the extension method.


public static class StaticDistinct
{
       public static IEnumerable<TSource> DistinctBy<TSource, TKey>
        (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
              HashSet<TKey> knownKeys = new HashSet<TKey>();
              foreach (TSource element in source)
               {
                    if (knownKeys.Add(keySelector(element)))
                    {
                         yield return element;
                    }
                }
          }
 }

// USAGE
var distinctUsers = users.DistinctBy(x => x.EmailId).ToList();

This example also demostrate what are extension methods and syntax of extension method.

Extension Methods:

#1) These are static methods, so these method should be surronded by static class

#2) These method signature would start this keyword. Let’s say you want to write extension method to string then the method would be some thing like below.


// DEFINE EXTENSION METHOD
 public static string ImExtensionMethod(this string value)
 {
   return "Hurray! I am EXTENSION method";
 }

//USAGE
  string whoAreYou = "Hello";
  whoAreYou.ImExtensionMethod();

By now you should be knowing why did we define DISTINCTBY as extension method

Happy Kooding…. Hope this helps!

Advertisements

Find No of Lines in Files (In a directory & sub directory)

Hi All,

In this article, we will perform below tasks & this code base is window forms

1.       Find  list of files present in a directory & sub directory without calling function(s) recursively i.e. avoid recursive function

2.       Calculate no of lines of code available in all files under a directory & sub directory

This code is Window Form code:

1.       Open a new windows form application

2.       Add following  controls to the form1,assign controls NAME & TEXT properties respectively

a.       Label  à Name: lblPath, Text: Files Path

b.      Label à Name: lblFileTypes, Text: File Types

c.       Label à Name: lblLinesCount, Text : No of Lines

d.      Label à Name: lblFilesCount, Text : No of Files

e.      Textbox à Name : txtPath, Text:

f.        Button à Name: btnCalculate, Text: Calculate Lines

3.       Declare below global variable inside the form1 class

int linesCount = 0;

4.       Add below code in btnCalculate click event with inline comments to each code statement

private void btnCalculate_Click(object sender, EventArgs e)

{

/* below code, declares array list object & call GetAllFiles which will take folder path which is to be crawled & this function returns all files in the directory & sub directories */

ArrayList filesList = GetAllFiles(txtPath.Text.ToString());

/* below code, for loop is to read each file from filesList object & sum no of files present in each file */

foreach (string fileName in filesList)

{

/* below code, find all lines present in a files */

string[] lines = File.ReadAllLines(fileName);

/* below code, finds lines count & add it to global linesCount variable*/

linesCount += lines.Length;

}

/* below code, assigns not of lines present in all files to label  */

lblLinesCount.Text += Convert.ToString(linesCount.ToString());

/* below code, assigns total files crawled by our code */

lblFilesCount.Text += Convert.ToString(filesList.Count.ToString());

}

5.       Now let’s add GetAllFiles function, with inline comments to each code statements

/* below function takes director path to be crawled */

private ArrayList GetAllFiles(string directory)

{

/* below code, declares Arraylist object */

ArrayList totalFilesList = new ArrayList();

/* below code, does a preliminary checks to see if the directory path is not empty, if it is empty simply returns i.e. exit the function execution*/

if (directory == string.Empty)

return totalFilesList;

/* below code, creates search option object to crawl all sub directories in a parent directory. The beauty of this is, by using this we can avoid calling of function recursively to find sub directories */

SearchOption sop = SearchOption.AllDirectories;

/* below code, get all files in a directories & sub directories with the extensions .cs

Directory.GetFiles returns files list & take 3 parameters 1. Root directory path 2. Files to be read with extension .cs 3. SearchOption object */

string[] files = Directory.GetFiles(directory, “*.cs”, sop);

/* below code, add up the filesList to main arraylist object */

totalFilesList.AddRange(files);

/* below code, return arraylist with list of files */

return totalFilesList;

}

6.       Now execute & the output

Happy Kooding… Hope this helps!