• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 278
  • Last Modified:

Grouping items in. NET but not use DataTable

I'm writing a C# console program(3.0 framework) that will be performing file operations based on the given file paths.

At the end of the processing, I would like to create a summary file of what was processed....

Example...

C:\Path1 - 45 files processed
C:\Path2 - 52 files processed

I can create a datatable, and add rows as I process each file, example...

ColumnPath, ColumnCount
C:\Path1 - 1
C:\Path1 - 1
etc....

And then at the end of the processing, group them by path, and sum up the count, and create the summary, but is there a better way to do this other than using a DataTable?

Additional Note: I don't have control over the order of the given filepaths. So on the first run I may get...
C:\Path1\processme.txt
C:\Path2\processme.txt
C:\Path1\processme.txt

So, I kind of have to do it on the fly.
0
silentthread2k
Asked:
silentthread2k
  • 3
  • 2
4 Solutions
 
Todd GerbertIT ConsultantCommented:
You can use a Dictionary<TKey, TValue> object.

The code below creates a dictionary with a string key, and int value: Dictionary<string, int>

The ProcessFile function just returns a random number for the sake of an example.
0
 
Todd GerbertIT ConsultantCommented:
Sorry, meant this to go along with my post...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace ConsoleApplication1
{
	class Program
	{
		static Random rnd = new Random(DateTime.Now.Millisecond);

		static void Main(string[] args)
		{
			Dictionary<string, int> summaryTable = new Dictionary<string,int>();

			string[] fileNames = {"C:\\path1\\processme.txt","C:\\path2\\processme.txt","C:\\path1\\processme.txt"};

			foreach (string file in fileNames)
			{
				if (!summaryTable.Keys.Contains(file))
					summaryTable.Add(file, 0);

				summaryTable[file] += ProcessFile(file);
			}
			
			foreach(string file in summaryTable.Keys)
				Console.WriteLine("{0}: {1} items processed.", file, summaryTable[file]);

			Console.ReadKey();
		}

		static int ProcessFile(string FileName)
		{
			return rnd.Next(1, 101);
		}

	}
	
}

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
You could also just add all the file paths to a List and then use LINQ to group/count them...
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Fernando SotoCommented:
If you are using the .Net Framework 3.5 I you can use Linq, I do not believe it is available in 3.0.

The code snippet below takes the directory C:\Temp and enumerates all of its directories and files and displays total file count of each directory and file names.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var results = from file in GetFiles("C:\\Temp")
                          group file by file.DirectoryName.ToLower() into filegroup
                          orderby filegroup.Key
                          select new { Group = filegroup, FileCount = filegroup.Count() };

            foreach (var dir in results)
            {
                Console.WriteLine("Directory = {0} Total Files = {1}", dir.Group.Key, dir.FileCount);
                foreach (var file in dir.Group)
                {
                    Console.WriteLine("\t{0}", file.Name);
                }
            }

            Console.ReadLine();

        }

        static IEnumerable<System.IO.FileInfo> GetFiles(string path)
        {
            if (!System.IO.Directory.Exists(path))
                throw new System.IO.DirectoryNotFoundException();

            string[] fileNames = null;
            List<System.IO.FileInfo> files = new List<System.IO.FileInfo>();

            fileNames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);
            foreach (string name in fileNames)
            {
                files.Add(new System.IO.FileInfo(name));
            }
            return files;
        }
    }
}

Open in new window

0
 
Todd GerbertIT ConsultantCommented:
@Idle_Mind

For the sake of my own edification, a LINQ code snippet?
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Take a peek at Fernando's post right above...  =)

They look similar to a SQL statement:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_25021421.html#26183602

See: http://msdn.microsoft.com/en-us/library/bb397933.aspx
0

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now