Return to Snippet

Revision: 59941
at October 11, 2012 01:35 by ed_trench


Initial Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CentreFolderDeduper
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] centreFolders = Directory.GetDirectories(args[0]);
            List<Folder> folders = new List<Folder>();

            foreach(var centreFolder in centreFolders)
            {
                if (centreFolder.IndexOf('-') != -1)
                {
                    var newFolder = new Folder {
                                        ShortName = centreFolder.Left(centreFolder.IndexOf('-')),
                                        DateCreated = System.IO.File.GetCreationTime(centreFolder)};
                    folders.Add(newFolder);
                }
            }
                        
            var duplicateFolders = from f in folders
                                   group f by f.ShortName into g
                                   where g.Count() > 1
                                   select new { CentreFolderName = g.Key,
                                                CentreFolderNameCount = g.Count(),
                                                LastDateCreated = g.Max(f => f.DateCreated) };

            Console.WriteLine(duplicateFolders.Count());
            ObjectDumper.Write(duplicateFolders);
            Console.ReadKey();
        }
    }
}

class Folder
    {
        public String Directoty { get; set; }
        public String ShortName { get; set; }
        public DateTime DateCreated { get; set; }
    }

 public static string Left(this string str, int count)
        {
            if (string.IsNullOrEmpty(str) || count < 1)
                return string.Empty;
            else
                return str.Substring(0, Math.Min(count, str.Length));
        }

Initial URL

                                

Initial Description
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<Folder>. Also, amended the LINQ statement to get the MAX(Date Created) .

Initial Title
C# LINQ & Extension method continued

Initial Tags
extension

Initial Language
C#