I need compare file names with user input and have to display the files that are matching. I am using a recursive function for that.I stored the matched files in a list.But I got problems when I return the list. How to return values from a function which is called recursively?
Option 1 (better approach):
You can pass a string to the recursive method, append the filename with a comma to the string inside the recursive function and pass the same string when the recursive function is called from within itself. Better option would be to use a StringBuilder rather than a string.
Option 2 (not recommended):
You might want to declare a global variable have the function append data to it.
In both the options you could use a List<> if more appropriate.
It's trivial; you set an exit case:
function f (List m){
if( y )
{
m.Add(k);
return f(m);
}
return m;
}
You can 'return' data using parameters. For example:
public void MyRecursiveFunction(List<string> files, int depth)
{
files.Add("...");
if (depth < 10)
{
MyRecursiveFunction(files, depth + 1);
}
}
Pass the list in as a param. All classes are 'pointers' so when its modified inside the func the changes appears everywhere. If i didnt answer your question heres something i written a few days ago.
oops, this doesnt show passing a list around. However you essentially doing the below but with a list instead of an int? pass the list as a param. Also you can lookup the ref keyword but thats not necessary.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DeleteWhenBelow
{
class Program
{
static void Main(string[] args)
{
var dir = @"C:\Users\FixLoc\Documents\";
var count = findAndDelete(dir, false, 1);
Console.WriteLine(count);
}
static long findAndDelete(string folder, bool recurse, long filesize)
{
long count = 0;
if(recurse)
{
foreach (var d in Directory.GetDirectories(folder))
{
count += findAndDelete(d, recurse, filesize);
}
}
foreach (var f in Directory.GetFiles(folder))
{
var fi = new FileInfo(f);
if (fi.Length < filesize)
{
File.Delete(f);
count++;
}
}
return count;
}
}
}
Since you are using C# 3.0, you could use LINQ to simplify your problem:
var expectedNames = getExpectedFilenames();
var matchingFiles = directoryInfo
.GetFileSystemInfos()
.SelectMany(fsi => fsi.GetFileSystemInfos())
.OfType<FileInfo>()
.Where(fi => expectedNames.Contains(fi.Name));
I have not tested the above code, so it might need some tweaking... The GetFileSystemInfos will get both DirectoryInfo and FileInfo objects, then project the same operation onto each returned entry with SelectMany. SelectMany will flatten the hierarchical structure. OfType filters out directories. The Where searches the set of expected file names against each file name from your projection.