c# exclude hyphen from directory.getdirectories
I would like to use the Directory.GetDirectories met开发者_如何转开发hod to get all directories with some exclusions. In particular I need to exclude directories that have a hyphen in them. I already found out regular expressions to not work as search patterns. What search pattern would I use?
Maybe a linq query would be sufficient?
//query notation
var result = from d in Directory.GetDirectories(path)
where !d.Contains("-")
select d;
//'dot' notation
var result2 = Directory.GetDirectories(path)
.Where(dir => !dir.Contains("-"));
EDIT(More explanation)
The solution above is called "LINQ to Objects". It is a way of querying collections that implement IEnumerable
or IEnumerable<T>
interface. The GetDirectories
method returns Array
of string that is eligible to use Linq. There is a lot of stuff about Linq on the internet. To see te power of Linq flick through these examples on MSDN: 101 Linq Samples. BTW Linq is useful to retrieve data from various sources like XML, databases etx.
System.Collections.ObjectModel.Collection<string> resultDirs=new System.Collections.ObjectModel.Collection<string> ();
foreach (string dir in System.IO.Directory.GetDirectories("path"))
{
if (!dir.Contains("-")) resultDirs.Add(dir);
}
Not LINQ way:
static void Main(string[] args)
{
string StartingPath = "c:\\";
List<string> mydirs = new List<string>(); // will contains folders not containing "-"
foreach (string d in Directory.GetDirectories(StartingPath))
{
if (!(d.Contains("_")))
{
mydirs.Add(d);
}
foreach (string dir in mydirs)
{
Console.WriteLine(dir);
}
}
}
}
精彩评论