我正在研究C#2.0 / .NET 2.0中的一个问题,我有一个Sortedlist,想要搜索所有的“值”。 (而不是“Sort”列表的“键”)用于某个子字符串,并计算出有多少次出现。

这就是我要做的事情:

{
   Sortedlist<string,string> mySortedList;
   // some code that instantiates mySortedList and populates it with data
   List<string> myValues = mySortedList.Values;  // <== does not work
   int namesFound = myValues.FindAll(ByName(someName)).Count;
}

当然,这不起作用,因为mySortedList.Values返回一个IList,而“myValues”则返回一个IList。是一个清单。我试过“铸造” IList,以便它被myValues接受,但它似乎不起作用。

当然,我可以在“foreach”中循环mySortedList.Values。循环,但我真的不想这样做。

有人有任何建议吗?

EDIT-1:好的,看起来好像没有本地方式可以轻松完成这项工作。我以为我只是错过了一些东西,但显然我不是。所以我想我只是想做一个“foreach”。在IList上。

感谢大家的反馈!我投票给大家1,因为我认为所有反馈都很好。再次感谢! : - )

EDIT-2:看起来CMS有我想要的答案。唯一需要注意的是(正如Qwertie指出的那样),因为它涉及将所有值复制到另一个List然后从头到尾搜索该列表,因此存在潜在的性能损失。所以对于短名单,这个答案是有效的。更长的名单?那取决于你决定......

有帮助吗?

解决方案

IList Interface 实现 IEnumerable ,您实际上可以使用 List&lt; T&gt; rel =“nofollow noreferrer”> List&lt; T&gt; (IEnumerable)构造函数

List<string> myValues = new List<string>(mySortedList.Values);

其他提示

您无法将Values属性强制转换为List&lt; string&gt;因为它不是List&lt; string&gt; - 它是Dictionary&lt; TKey,TValue&gt; .ValueCollection。

但是如果您使用 LinqBridge (适用于带有C#3.0的.NET Framework 2.0)使用LINQ可以很容易地解决这个问题:

SortedList<string, string> m = ...;
int namesFound = m.Values.Where(v => v.Contains("substring")).Count();

(如果你还在C#2.0上,你可以使用穷人的LINQ 而是稍微多做一些工作)

太糟糕了,你在.Net 2.0。这正是LINQ的用途。 ;)

你不能真的这样做,因为FindAll()是List的成员。您可以在mySortedList.Values上创建一个新的List,但这似乎是一种浪费,因为需要分配一个新对象和底层数组来调用一个函数。

我只是在某个类中为名为FindAll()的列表编写一个实用函数,然后传递你的IList和委托。

您是否尝试过 SortedList GetValueList 了吗?这将给你一个 IList 的值。

    static void Main(string[] args)
    {
        string someName = "two";
        SortedList<string, string> mySortedList = new SortedList<string,string>()
        {
            {"key1", "This is key one"},
            {"key2", "This is key two"},
            {"key3", "This is key three"},
        };

        int namesFound = mySortedList.Values.Where(i => i.Contains(someName)).Count();
        Console.WriteLine(namesFound);
        Console.ReadKey();
    }

在Framework 2.0中,也许可以这样做:

    static void Main(string[] args)
    {
        string someName = "two";
        SortedList<string, string> mySortedList = new SortedList<string,string>()
        {
            {"key1", "This is key one"},
            {"key2", "This is key two"},
            {"key3", "This is key three"},
        };

        int namesFound = FindAll(mySortedList.Values, someName).Count ;
        Console.WriteLine(namesFound);
        Console.ReadKey();
    }
    public static IList<String> FindAll(IList<String> items, string item)
    {
        List<String> result = new List<string>();
        foreach (String s in items)
        {
            if (s.Contains(item))
            {
                result.Add(s);
            }
        }
        return result;
    }

但那是你真正不想做的事。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top