开发者

Find Index from List

I have a Dictionary that contains thread Information Dictionary<String,Thread>

"2FF"
"2IE"
"7CH"

etc

what i know is integers 2,7 etc what i want to know that in Dictionary how many strings contain the given integer if it is there then get tha开发者_JAVA技巧t string

Eg

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

}


With LINQ syntax:

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

With traditional syntax:

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

If you only need to count them and you don't care about the Thread objects, you can use:

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

Note that you need a using System.Linq directive.


Maybe a List<CustomClass> would be a better choice here where CustomClass would look like:

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

(Better property names are alway good, of course :-) )

A dictionary is not sutitable if you do not know the exact keys or only parts of them.

You could then use LINQ to find out what you want, e.g.:

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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜