I have the following code:
string[] projects = Directory.GetDirectories(dir, "*", SearchOptions.TopDirectoryOnly);
string[] issues = Directory.GetFiles(dir, "*.txt", SearchOptions.AllDirectories)
foreach (string project in projects)
{
var filteredIssues = from fi in issues where fi.Contains(project) select new { f = fi };
foreach(string issue in filteredIssues)
{
// do something
}
}
But this won't compile and gives me the following error:
Cannot convert type 'AnonymousType#1' to 'string'
I was looking at this example: http://www.dotnetlearners.com/linq/linq-to-string-array-with-example.aspx
And this SO question: How do I use LINQ Contains(string[]) instead of Contains(string)
But I wasn't really sure what uid is in that particular case or how to apply the solution to my problem.
I also tried
var filteredIssues = issues.Select(x => x.Contains(project)).ToArray();
But that returns an array of bools.
dir points to a "Projects" folder which will contain N uniquely named folders. Each folder there will contain an "Active" and "Archived" folder containing however many text files (which is what issues contains, and I'm effectively just trying to filter issues on a Project basis to load them into the UI grouped by project)
Ultimately I want the LINQ equivalent of this SQL statement:
SELECT issue FROM issues WHERE issue LIKE '%project%'
Although now as I'm writing this I realize I can just simply do string[] issues = Directory.GetFiles(project, "*.txt", SearchOptions.AllDirectories) from within the first foreach loop rather than outside. But I'm still curious how you could filter a collection of strings based on values that contain another value.
You can use Where to filter a collection. Like so:
var filteredIssues = issues.Where(x => x.Contains(project)).ToArray()
Select is for projecting one IEnumerbale<Type> to another IEnumerbale<Type2>. Think of it like Mapping, you can cherry pick what to map to the target type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With