• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 282
  • 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
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

 
Fernando SotoRetiredCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

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