1

Is it possible to search in array by word using linq ?

Example:

My array looks like:

AA BB CC DD EE

BB CC DD EE FF

AA BB CC DD EE

I want to return lines where first column is "AA".

I am using linq to sort my array by first column:

sorted = array.OrderBy(o => o[1]).ThenBy(t => t[1]).ToArray();

I try to create somethink like Find an item in List by LINQ?

string search = "AA";

sorted = array.Single(s => s == search);

But it will not work for me beacuse I am using a 2D array.

I'd like to return an array like:

AA BB CC DD EE

AA BB CC DD EE

Desmond Lee
  • 707
  • 6
  • 17
Kenny Pattern
  • 49
  • 1
  • 9

2 Answers2

1

A simple where will do the trick:

var result = array.Where(inner => inner.FirstOrDefault() == "AA");
Desmond Lee
  • 707
  • 6
  • 17
1

Try something like that;

var newArray = array.Where(x => x.Length > 0 && x[0] == "AA").ToArray();

Also, you should consider the subarray length to prevent unexpected out of index error.

lucky
  • 12,734
  • 4
  • 24
  • 46