开发者

Linq to objects variation of contains

All clear for

string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };

IEnumerable<string> query = names
    .Where   (n => n.Contains ("a"))

What actually I need

string[] providers = { "gmail", "yahoo", "h开发者_开发百科otmail" , "something" };

and determine with LINQ ( not necessarily returning IEnumerable , bool will do ) whether certain email address somebody@something.com is from this provider list, i.e. element of array providers is case-insensitive substring of email address.


Will you be dealing with individual emails or a collection of em?

// individual
var email = ...;
var isValid = providers.Any(p => email.IndexOf(p, StringComparison.OrdinalIgnoreCase) != -1);

// collection
var emails = new[] { ... };
var validEmails = emails.Where(e => providers.Any(p => e.IndexOf(p, StringComparison.OrdinalIgnoreCase) != -1));


you can use this.

string[] providers = { "gmail", "yahoo", "hotmail", "something" };
string inputEmail1 = "test@gmail.com";
string inputEmail2 = "test@gmail2.com";
var query = from n in providers
            where inputEmail1.ToLower().Contains("@" + n + ".")
            select n;

Console.WriteLine(query.Count()); //For inputeEmail1,Print 1. For inputeEmail2, it will print 0


This will check if the provided email address's domain exists in the list of domains. It will provide a bool.

string email = "me@hello.com";

string[] domains = new string[]{"hello", "goodbye"};

bool exists = new List<string>(domains).Exists(x => email.Conatains(string.Format(@"@{0}\.", x);


I'm guessing that you want to do a case insensitive match of the text between the '@' and the first '.'.

So, here's my approach:

var providers = new []
    { "gmail", "yahoo", "hotmail", "something" };

var inputEmail = "test@gmail.com";

var match = inputEmail.Split('@')[1].Split('.')[0];
// You should probably expand this out to check for error in the input string.

Func<string, bool> isMatch =
    p => String.Compare(match, p, true) == 0;

var query =
    from p in providers
    where isMatch(p)
    select p;

var contains = query.Any();

I try to remove the detail of my query out to a Func to make the query sort of "extra simple".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜