我有一个字符串,其名称是从数据库返回的。我需要将其匹配为其他格式;也就是说,我以“ John Smith”的形式获取数据,并且需要将其与“ Smith,John”进行匹配,这是我必须选择的选项之一。
我尝试使用All
和Contains
来检查是否存在这样的选项,但这似乎失败了:
bool check = false;
string result = string.Empty;
string myName = "John Smith";
//note the space, this is intentional, as whether there is a space after the comma is inconsistent
var myOptions = new List<string> { "Smith,John", "Doe, Bob" };
var myKeywords = myName.Split(' ').ToList();
if(myKeywords.All(myOptions.Contains))
{
check = true;
}
给出myName = "John Smith"
,我希望result
等于Smith,John
(因为它是MyOptions列表中的一个选项)。
编辑:谢谢您的评论,现在我有
string result = string.Empty;
string MyName = "John Smith";
//note the space, this is intentional, as whether there is a space after the comma is inconsistent
var MyOptions = new List<string> { "Smith,John", "Doe, Bob" };
var MyKeywords = MyName.Split(' ').ToList();
foreach (var option in MyOptions)
{
if (MyKeywords.All(option.Contains)) result = option;
}
这似乎有效。如果有人认为可以改进,请指出。
编辑:我的下一个尝试,这应该将“约翰·史密斯”与“史密斯·约翰”和“史密斯·约翰”匹配,而不是“艾伦·史密斯,约翰”:
List<string> temp = MyName.Split(' ').ToList();
string final = string.Empty;
final = string.Join("", temp.Skip(1)) + "," + temp.First();
foreach (var option in MyOptions)
{
if(option.Replace(" ", string.Empty).Equals(final))
{
result = option;
break;
}
}
最终编辑:感谢@ er-mfahhgk,进行了一些修改,与上一次尝试相比,我以更优雅的方式获得了所需的结果:
string result = string.Empty;
string myName = "John Smith";
var myOptions = new List<string> { "Smith,John", "van der val, Jeroen" };
var myKeywords = MyName.Split(' ').ToList();
result = MyOptions.Find(x => MyKeywords.All(y => x.Replace(" ", string.Empty).Split(',').Contains(y)));
答案 0 :(得分:2)
当您的if
与true
完全匹配时,下面的John Smith
可以Smith,John
。
if (MyOptions.Any(x => MyKeywords.All(y => x.Split(',').Contains(y))))
{
check = true;
}
答案 1 :(得分:0)
尝试遍历myOptions。如下更改代码-
bool check = false;
string result = string.Empty;
string myName = "John Smith";
//note the space, this is intentional, as whether there is a space after the comma is inconsistent
var myOptions = new List<string> { "Smith,John", "Doe, Bob" };
var myKeywords = myName.Split(' ').ToList();
foreach(string s in myOptions)
{
if (myKeywords.All(s.Contains))
{
check = true;
}
}
但是,这只是为了给您一个想法,在这种情况下,您必须测试所有方案。即使myOptions条目(名字和姓氏不完全相同)也将起作用
答案 2 :(得分:0)
类似的东西吗?
var myOptions = new List<string> { "Smith,John", "Doe, Bob" };
string myName = "John Smith";
var myKeywords = myName.Split(' ').ToList();
foreach (var myOption in myOptions)
{
if (Regex.Match(myOption,$"{myKeywords[1]},\\s?{myKeywords[0]}").Success)
{
result = myOption;
}
}