如何在 ObservableCollection 中找到 partially-matching 值?
How can I find partially-matching values in an ObservableCollection?
我想在我的 ObservableCollection
中搜索任何我能找到的特定项目的匹配项。在这种情况下,我的项目是 "artist"。基本上它只是一个搜索栏,用户可以在其中键入艺术家姓名。
我这样做了并且有效,但用户必须输入完全相同的值:
//user type "david guetta"
if (myCollection.Any(x => x.artist== input.Value))
{
//...
}
如何在我的 collection 中找到部分匹配项,用户可以在其中键入 "david" 并检索包含该字符串的所有艺术家?
我尝试将正则表达式与字符串数组一起使用,效果也不错,但我无法对 collection.
执行同样的操作
string[] artists=
{
"Malcom George",
"Willis H. David",
"David Bowie",
"Davidson"
};
string pattern = input.Value;
foreach (string s in artists)
{
if (Regex.IsMatch(s, pattern, RegexOptions.IgnoreCase))
{
// ...
}
}
您可以检查 Any
的谓词,而不是相等比较,只需检查 string
是否包含输入 string
.
你可以这样做:
myCollection.Any(x => x.artist.Contains(input.Value))
如果您需要不区分大小写的搜索,您可以执行以下操作:
myCollection.Any(x => x.artist.IndexOf(input.Value, StringComparison.InvariantCultureIgnoreCase) >= 0)
要获取对象,您可以使用 Where 方法而不是 Any
myCollection.Where(x => x.artist.Contains(input.Value))
myCollection.Where(x => x.artist.IndexOf(input.Value, StringComparison.InvariantCultureIgnoreCase) >= 0)
我想在我的 ObservableCollection
中搜索任何我能找到的特定项目的匹配项。在这种情况下,我的项目是 "artist"。基本上它只是一个搜索栏,用户可以在其中键入艺术家姓名。
我这样做了并且有效,但用户必须输入完全相同的值:
//user type "david guetta"
if (myCollection.Any(x => x.artist== input.Value))
{
//...
}
如何在我的 collection 中找到部分匹配项,用户可以在其中键入 "david" 并检索包含该字符串的所有艺术家?
我尝试将正则表达式与字符串数组一起使用,效果也不错,但我无法对 collection.
执行同样的操作string[] artists=
{
"Malcom George",
"Willis H. David",
"David Bowie",
"Davidson"
};
string pattern = input.Value;
foreach (string s in artists)
{
if (Regex.IsMatch(s, pattern, RegexOptions.IgnoreCase))
{
// ...
}
}
您可以检查 Any
的谓词,而不是相等比较,只需检查 string
是否包含输入 string
.
你可以这样做:
myCollection.Any(x => x.artist.Contains(input.Value))
如果您需要不区分大小写的搜索,您可以执行以下操作:
myCollection.Any(x => x.artist.IndexOf(input.Value, StringComparison.InvariantCultureIgnoreCase) >= 0)
要获取对象,您可以使用 Where 方法而不是 Any
myCollection.Where(x => x.artist.Contains(input.Value))
myCollection.Where(x => x.artist.IndexOf(input.Value, StringComparison.InvariantCultureIgnoreCase) >= 0)