我收到了带有字符串属性的结构。给定一个字符串数组我想检查是否有任何结构内部字符串匹配数组中的一些。我是这样做的:
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。这是一种正确的方法吗?它有效吗?
答案 0 :(得分:2)
您还可以使用HashSet
,其性能应与Dictionary
类似:
var set = new HashSet<string>(
List.Select(x => x.s),
StringComparer.InvariantCultureIgnoreCase);
return arr.Any(set.Contains);
答案 1 :(得分:1)
最有效的方法是根据你拥有的结构集创建一个字典。
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.
}
}
答案 2 :(得分:0)
你可以做这样的事情
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();
}
}