从列表中查找索引

时间:2011-01-11 19:13:51

标签: c# multithreading

我有一个包含帖子信息Dictionary<String,Thread>

的词典
"2FF"
"2IE"
"7CH"

我所知道的是整数2,7等我想知道在Dictionary中有多少字符串包含给定的整数,如果它在那里那么得到那个字符串

例如

String GetString(int integer)
{
//if Dictionary contains given intgr return whole string in which that integer is present
}

}

3 个答案:

答案 0 :(得分:3)

使用LINQ语法:

var matchingThreads = from pair in dictionary
                   where pair.Key.StartsWith(number.ToString())
                   select pair.Value;

使用传统语法:

var matchingThreads = dictionary
                .Where(pair => pair.Key.StartsWith(number.ToString()))
                .Select(pair => pair.Value);

如果您只需计算它们并且您不关心Thread个对象,则可以使用:

int count = dictionary.Keys.Count(key => key.StartsWith(number.ToString()))

请注意,您需要using System.Linq指令。

答案 1 :(得分:0)

可能是List&lt; CustomClass&gt;在CustomClass看起来像是一个更好的选择:

public sealed class CustomClass
{
   public Thread Thread { get; set; }
   public string String { get; set; }
}

(更好的物业名称总是好的,当然:-))

如果你不知道确切的键或只是部分词,那么字典是不可分割的。

然后,您可以使用LINQ找出您想要的内容,例如:

int count = list.Where(c => c.String.StartsWith(integer.ToString())).Count();
//or
IEnumerable<string> strings = list.Where(c => c.String.StartsWith(integer.ToString())).Select(c => c.String);

答案 2 :(得分:0)

public IEnumerable<string> GetMatchingKeys(int value)
{
    var valueText = value.ToString();

    return _dictionary.Keys.Where(key => key.Contains(valueText));
}