开发者

ASP.NET Processing lambdas

What is the code clean up needed on the following linq inorder to validate Email IDs

Error: var validemails = emails.Where(p=>IsValidFormat(p)).Select;

 Dictionary<int, string> emails = new Dictionary<int, string>();
 emails.Add(1, "Marry@开发者_如何转开发yahoo.com");
 emails.Add(2, "Helan@gmail.com");
 emails.Add(3, "Rose");
 emails.Add(4, "Ana");
 emails.Add(5, "Dhia@yahoo.com");




public static bool IsValidFormat(string InputEmailID)

{
    var format =
                 @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}.\.[0-9]{1,3}\.)|
                 (([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

                  Regex Rex=new Regex(format);
                  return Rex.IsMatch(InputEmailID);

 }

Error Report : Can not convert from 'System.Collections.Generic.KeyValuePair' to 'string'


You need to send the function a string, not a KeyValuePair

var validemails = emails.Where(p=>IsValidFormat(p.Value)).Select(kv => kv.Value);


It sounds like email is a dictionary rather than a simple IEnumerable<string>

You want something more like this:

var validemails = emails.Where(p=>IsValidFormat(p.Key));

or

var validemails = emails.Where(p=>IsValidFormat(p.Value));

depending on whether the "emailid" is the key or the value in your dictionary.

I'd also refactor you validation method like this:

public static bool IsValidEmail(this string InputEmailID)
{
    var format =
             @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}.\.[0-9]{1,3}\.)|
             (([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

    Regex Rex=new Regex(format);
    return Rex.IsMatch(InputEmailID);
}

So you can call the validation like this:

var validemails = emails.Where(p=>p.Key.IsValidEmail());


I just experimented with this code:

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var emails = new Dictionary<int, string>();

            emails.Add(1, "Marry@yahoo.com");
            emails.Add(2, "Helan@gmail.com");
            emails.Add(3, "Rose");
            emails.Add(4, "Ana");
            emails.Add(5, "Dhia@yahoo.com");

            var validemails = emails.Where(p => IsValidFormat(p.Value)).ToList();
        }


        public static bool IsValidFormat(string inputEmailId)
        {
            const string format = @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}.\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            var rex = new Regex(format);
            return rex.IsMatch(inputEmailId);
        }
    }
}

Which looks to have worked. I'm not 100% sure what is going on, but the key is that you needed to use p.Value.

I'm sure someone will explain the finer details - I'm hoping to learn a bit from this also.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜