In my C# Form script, I have array which contains like 2-3k elements. I need to find a specific value in that array but without applying for loop to it. Looping trough 2-3k elements will cause couple of seconds delay, and i dont want that. This is similar to Mysql database for a website.
In PHP websites i was using where clause on indexed database, so even if the table had 1 milion rows, i was able to get the only row i needed in 0.020 second. Is there something similar for C#?
Here is what i'm trying to achieve.
using System;
using System.Linq;
public class Program
{
public static float[] data = {140, 160, 170, 180, 190, 54235243,234,4213,1234,543,1234,3215,52134,1234,222,333,444,555,666,777,888,999};
public static void Main()
{
var queryLowNums =
from num in data
where num > 140 and num < 170
select num;
// num should be 160
}
}
This code above is invalid ofc, im just trying to give example of what im trying to do. Is there such syntax/command or whatever, anything that can help me in this situation. Looping trough 2-3k elements will take like a second maybe or 2 seconds idk. I know that if i have the index of a given element, it will load it directly without the need of for loop. But idk how to achieve that.
CodePudding user response:
Use List
var list = new List<float>() { 140, 160, 170, 180, 190 };
var index = list.IndexOf(160);
var values = list.Where(x=>x > 140 && x < 190); //it`s work very fast
CodePudding user response:
try this
float[] data = { 140, 160, 170, 180, 190, 54235243, 234, 4213, 1234, 543, 1234, 3215, 52134, 1234, 222, 333, 444, 555, 666, 777, 888, 999 };
float queryLowNums = 0;
var startIndex = 0;
Parallel.For(startIndex, data.Length, (j, state) =>
{
if (data[j] > 140 && data[j] < 170)
{
queryLowNums = data[j];
state.Break();
}
});
output
160
or if you are expecting several numbers
var primeNumbers = new ConcurrentBag<float>();
Parallel.ForEach(data, number =>
{
if (number > 140 && number < 170)
{
primeNumbers.Add(number);
}
});
using a hash table would be much faster, but in your case if you don't have it , it takes less time to find an item then to create a hash table if it is not exist. The same about sorting algorithms.