[英]Matching invariant strings with LINQ
我得到了具有字符串属性的结构的集合。 给定一个字符串数组,我想检查内部字符串是否与该数组中的某些字符串匹配的任何结构。 我这样做是这样的:
struct S
{
public string s { get; set; }
}
private List<S> List = new List<S>(); // populated somewhere else
public bool Check(params string[] arr)
{
return (from s1 in List
select s1.s into s1
where !string.IsNullOrEmpty(s1)
join s2 in arr on s1.ToLowerInvariant() equals s2.ToLowerInvariant() select s1).Any();
}
简单来说,我只想实现StringComparison.InvariantCultureIgnoreCase。 这是正确的方法吗? 有效率吗?
您还可以使用HashSet
,其性能应与Dictionary
相似:
var set = new HashSet<string>(
List.Select(x => x.s),
StringComparer.InvariantCultureIgnoreCase);
return arr.Any(set.Contains);
这样做的最有效方法是根据您拥有的结构集合创建字典。
var dictionary = list.ToDictionary(item=>item.s.ToLowerInvariant(),item=>item);
然后,您可以遍历字符串数组(O(n)):
foreach(item in array)
{
S value;
// This is an O(1) operation.
if(dictionary.TryGetValue(item.ToLowerInvariant(), out value)
{
// The TryGetValue returns true if the an item
// in the dictionary found with the specified key, item
// in our case. Otherwise, it returns false.
}
}
你可以做这样的事情
class Program
{
struct MyStruct
{
public string Data { get; set; }
}
static void Main(string[] args)
{
var list = new List<MyStruct>();
list.Add(new MyStruct { Data = "A" });
list.Add(new MyStruct { Data = "B" });
list.Add(new MyStruct { Data = "C" });
var arr = new string[] { "a", "b" };
var result = (from s in list
from a in arr
where s.Data.Equals(a, StringComparison.InvariantCultureIgnoreCase)
select s).ToArray();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.