Reputation: 75
I have an array that stores some information.
I search this array to match the first column using this code:
int i = Array.IndexOf(ARRAY, ARRAY.Where(x => x.Contains(VALUE)).FirstOrDefault());
But what I want to do is find the index that matches the first value and second value.
Something like this (if that makes sense):
int i = Array.IndexOf(ARRAY, ARRAY.Where(x => x.Contains(VALUE1)).FirstOrDefault() && Contains(VALUE2)).Second());
Edit on request:
static void Main(string[] args)
{
//get states
Console.WriteLine("state1");
string state1 = Console.ReadLine();
Console.WriteLine("state2");
string state2 = Console.ReadLine();
//read from csv
String[] statearray = File.ReadAllLines(@"C:\Test\States.csv");
var query = from line in statearray
let data = line.Split(',')
select new
{
Start = data[0],
Finish = data[1],
StatesCrossed = data[2],
};
//get index
int i = Array.IndexOf(statearray, statearray.Where(x => x.Contains(state1)).FirstOrDefault());
Console.ReadLine();
}
Where state 1
and state 2 ="NSW"
and where csv
is in the format:
NSW, NSW, 1
NSW, VIC, 2
Upvotes: 0
Views: 496
Reputation: 12797
Sample code
int index = query.Select((v, i) => new { Value = v, Index = i + 1 })
.Where(p => p.Value.Start == state1 && p.Value.Finish == state2)
.Select(p => p.Index)
.FirstOrDefault() - 1;
But you also need to trim your elements:
var query = from line in statearray
let data = line.Split(',')
select new
{
Start = data[0].Trim(),
Finish = data[1].Trim(),
StatesCrossed = data[2].Trim(),
};
Upvotes: 1