我正在研究C#2.0 / .NET 2.0中的一个问题,我有一个Sortedlist,想要搜索此SortedList的所有“值”(而不是“键”)以查找某个子字符串并计算多少有事件发生。
这就是我要做的事情:
{
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”是List。我尝试“施放”IList,以便myValues接受它,但它似乎不起作用。
当然,我可以在“foreach”循环中循环mySortedList.Values,但我真的不想这样做。
有人有任何建议吗?
EDIT-1:好的,看起来好像没有本地方式可以轻松完成这项工作。我以为我只是错过了一些东西,但显然我不是。所以我想我只是要对IList做一个“预告”。
感谢大家的反馈!我投票给大家1,因为我认为所有反馈都很好。再次感谢! : - )
EDIT-2:看起来CMS有我想要的答案。唯一需要注意的是(正如Qwertie指出的那样),因为它涉及将所有值复制到另一个List然后从头到尾搜索该列表,因此存在潜在的性能损失。所以对于短名单,这个答案是有效的。更长的名单?那取决于你决定......
答案 0 :(得分:2)
您无法将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,则可以使用Poor-man's LINQ代替更多工作)
答案 1 :(得分:2)
由于IList Interface实施IEnumerable,您实际上可以使用List<T> (IEnumerable) Constructor
获得List<T>
个值:
List<string> myValues = new List<string>(mySortedList.Values);
答案 2 :(得分:1)
太糟糕了,你在.Net 2.0。这正是LINQ的用途。 ;)
你不能真的这样做,因为FindAll()是List的成员。您可以在mySortedList.Values上创建一个新的List,但这似乎是一种浪费,因为需要分配一个新对象和底层数组来调用一个函数。
我只是在某个类中为名为FindAll()的列表编写一个实用函数,然后传递你的IList和委托。
答案 3 :(得分:1)
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;
}
但那是你真正不想做的事。
答案 4 :(得分:1)
你有没有试过SortedList
的{{3}}?这将为您提供IList
个值。