我有一个输入字符串数组,其中包含域\帐户形式的电子邮件地址或帐户名。我想建立一个只包含电子邮件地址的字符串列表。如果输入数组中的元素的形式为domain \ account,我将在字典中执行查找。如果在字典中找到密钥,那么该值就是电子邮件地址。如果未找到,则不会将其添加到结果列表中。下面将代码使上面的描述中明确:在LINQ中过滤时创建外部列表
private bool where(string input, Dictionary<string, string> dict)
{
if (input.Contains("@"))
{
return true;
}
else
{
try
{
string value = dict[input];
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
}
private string select(string input, Dictionary<string, string> dict)
{
if (input.Contains("@"))
{
return input;
}
else
{
try
{
string value = dict[input];
return value;
}
catch (KeyNotFoundException)
{
return null;
}
}
}
public void run()
{
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{ "gmail\\nameless", "[email protected]"}
};
string[] s = { "[email protected]", "gmail\\nameless", "gmail\\unknown" };
var q = s.Where(p => where(p, dict)).Select(p => select(p, dict));
List<string> resultList = q.ToList<string>();
}
虽然上面的代码工作(希望我没有在这里任何错字),有2个问题,我不跟上面一样:
- where()和select()中的代码似乎是冗余/重复的。
- 需要2次通过。第二遍从查询表达式转换为List。
所以我想直接在where()方法中添加到List resultList。我似乎应该能够这样做。下面的代码:
private bool where(string input, Dictionary<string, string> dict, List<string> resultList)
{
if (input.Contains("@"))
{
resultList.Add(input); //note the difference from above
return true;
}
else
{
try
{
string value = dict[input];
resultList.Add(value); //note the difference from above
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
}
我的LINQ表达式可以在1个单个语句是很好的:
List<string> resultList = new List<string>();
s.Where(p => where(p, dict, resultList));
或者
var q = s.Where(p => where(p, dict, resultList)); //do nothing with q afterward
这似乎是完美的,合法的C#LINQ。结果是:有时它可以工作,有时它不会。那么为什么我的代码不能可靠地工作,我该如何做到这一点呢?
满意你的答案,解决了我的两个问题。当我看到它只在部分时间内有效时,我以为我疯了。 LINQ懒惰评估解释它。 – 2010-03-29 06:02:13