开发者

How to get the name form the string[] array comparing to the number given

Actually i am working on a sample code of my own trail where i enter a mobile number and click on buttonso that a form will open on that form i would like to show the name of that coresponding number from the string[] array available in the form

Assume i have

string[] User = { "XYZ", "ABC", "DEF" };
string[] Number = { "1234567890", "2345678901", "345678901" };

开发者_如何学编程Assume i enter 1234567890 and click on enter i would like to display the corresponding name from the list avialable i.e XYZ.

I don't know whteher i explain my problem clearly or not but it is similar to the finding the contact available.

Any better method please let me know..


Use Dictionary<long, string> is what you need here.

Dictionary<long, string> nameFromNumber = new Dictionary<long, string>();

nameFromNumber.Add(1234567890, "XYZ");
nameFromNumber.Add(2345678901, "ABC");
...

Then to find the name of the inserted number you can do:

long numberToCheck = 12364567890;
if (nameFromNumber.ContainsKey(numberToCheck)//Contains(numberToCheck)
{
    string name = nameFromNumber[numberToCheck];
    ...
}

Edit: change the signature to long instead of int, thanks to @Kirill how pointed this out, Anyway I personally would use string instead so my method will accept more generic format of numbers such as 012-3456789


You can use LINQ:

var result = 
    Number.Zip(User, (a, b) => new { a, b }).ToDictionary(k => k.a, v => v.b);

Console.WriteLine(result["1234567890"]);


Use Array.IndexOf to find the index of the item within the first array. Then use that index to locate the corresponding value in the second array.

int index = Array.IndexOf(Number, "1234567890");
string name = User[index];

However, a structure that maps one value to another would be better here. In C# the Dictionary class serves this function, for example:

var peeps = new Dictionary<string, string> {
                                               { "1234567890", "Bob" }, 
                                               ...
                                           };
var peep = peeps["1234567890"]; // will throw if doesn't exist

To handle missing entries:

var peep;
if (!peeps.TryGet(number, out peep)) throw new SomeException("Nobody with that number.");


Hope this helps:

// Assuming you have entered a number in a textbox
string[] User = { "XYZ", "ABC", "DEF" }; 
string[] Number = { "1234567890", "2345678901", "345678901" }; 
foreach(string s in Number)
{
if(s == textBox1.Text)
{
MessageBox.Show(User[s]);
}
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜