Posted By

ed_trench on 10/11/12


Tagged

extension Linq


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

danfinrud55


C# LINQ & Extension method continued


 / Published in: C#
 

Also extended C# LINQ and Extension method (simple) to include the last (MAX) Date Created property, added a new Folder class (model) with properties and included them in a List. Also, amended the LINQ statement to get the MAX(Date Created) .

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6.  
  7. namespace CentreFolderDeduper
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. String[] centreFolders = Directory.GetDirectories(args[0]);
  14. List<Folder> folders = new List<Folder>();
  15.  
  16. foreach(var centreFolder in centreFolders)
  17. {
  18. if (centreFolder.IndexOf('-') != -1)
  19. {
  20. var newFolder = new Folder {
  21. ShortName = centreFolder.Left(centreFolder.IndexOf('-')),
  22. DateCreated = System.IO.File.GetCreationTime(centreFolder)};
  23. folders.Add(newFolder);
  24. }
  25. }
  26.  
  27. var duplicateFolders = from f in folders
  28. group f by f.ShortName into g
  29. where g.Count() > 1
  30. select new { CentreFolderName = g.Key,
  31. CentreFolderNameCount = g.Count(),
  32. LastDateCreated = g.Max(f => f.DateCreated) };
  33.  
  34. Console.WriteLine(duplicateFolders.Count());
  35. ObjectDumper.Write(duplicateFolders);
  36. Console.ReadKey();
  37. }
  38. }
  39. }
  40.  
  41. class Folder
  42. {
  43. public String Directoty { get; set; }
  44. public String ShortName { get; set; }
  45. public DateTime DateCreated { get; set; }
  46. }
  47.  
  48. public static string Left(this string str, int count)
  49. {
  50. if (string.IsNullOrEmpty(str) || count < 1)
  51. return string.Empty;
  52. else
  53. return str.Substring(0, Math.Min(count, str.Length));
  54. }

Report this snippet  

You need to login to post a comment.