【问题标题】:Matching invariant strings with LINQ使用 LINQ 匹配不变字符串
【发布时间】:2015-07-30 06:17:37
【问题描述】:

我得到了具有字符串属性的结构集合。给定一个字符串数组,我想检查是否有任何内部字符串与数组中的一些匹配的结构。我是这样做的:

    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。这是一个正确的方法吗?效率高吗?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您也可以使用HashSet,它的性能应该与Dictionary相似:

    var set = new HashSet<string>(
         List.Select(x => x.s),
         StringComparer.InvariantCultureIgnoreCase);
    
    return arr.Any(set.Contains);
    

    【讨论】:

    • 这里的好处是你告诉哈希使用哪个比较,而不是转换每个字符串。
    【解决方案2】:

    最有效的方法是根据您拥有的结构集合创建字典。

    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.
        }
    }
    

    【讨论】:

    【解决方案3】:

    你可以这样做

    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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 2015-07-29
      • 2022-11-28
      • 1970-01-01
      • 2011-03-11
      • 2011-05-20
      • 2019-09-03
      • 1970-01-01
      相关资源
      最近更新 更多