C#: How to gracefully pass multiple conditions to Equals()
I'm new to C#, and I'm trying to write a program that selects file types from a FileInfo list. So far I have something along the lines of:
List<FileInfo> files = new List<FileInfo>();
IEnumerable<FileInfo> result = files.Where(f=>f.Extensio开发者_如何转开发n.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)||
f.Extension.Equals(".gif", StringComparison.InvariantCultureIgnoreCase) );
etc
Obviously I'm not happy with this solution, but I don't know how to do this otherwise in a single call.
What's the better way to go about it?
Perhaps Enumerable.Contains. Just normalize the extension to lower (or upper) case first.
var source = ...;
var accepted = new [] { ".foo", ".bar" };
var selected = source.Where(i => accepted.Contains(i.Extension.ToLowerCase()));
Edit, I've actually used the implicit method-to-function conversions recently, so I feel like mentioning it:
bool ValidExtension (FileInfo f) {
// do whatever logic here, perhaps use same technique as above
}
var selected = source.Where(ValidExtension);
Ahh Will just beat me
var extentions = new List<string>() {".jpg", "gif"};
var files = new List<FileInfo>();
var result2 = files.Where(f => extentions.Contains(f.Extension));
Implement your own extension method like so:
class Program
{
static void Main(string[] args)
{
List<FileInfo> files = new List<FileInfo>();
IEnumerable<FileInfo> result = files.Where(f => f.Extension.AnyOf(".jpg", ".gif"));
}
}
public static class Extensions
{
public static bool AnyOf(this string extension, params string[] allowed)
{
return allowed.Any(a=>a.Equals(extension));
}
}
No need to introduce an extension method, it's built-in in Linq anyway:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<FileInfo> files = new List<FileInfo>();
files.Add(new FileInfo("OhNo.jpg"));
files.Add(new FileInfo("OhYes.jpg"));
files.Add(new FileInfo("OhMy.pcx"));
files.Add(new FileInfo("OhTrue.png"));
IEnumerable<FileInfo> result = files.Where(
f => new string[] { ".jpg", ".png" }.Contains(f.Extension));
foreach(var r in result) Console.WriteLine("{0}", r);
}
}
Output:
OhNo.jpg
OhYes.jpg
OhTrue.png
You can even do this(at least as tested on Mono, I'm in Mono now):
IEnumerable<FileInfo> result = files.Where(
f => new [] { ".jpg", ".png" }.Contains(f.Extension));
Here's how Rob Conery explains it: http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql/
精彩评论