0

I am starting in C# Linq. I would like to performance this query.

I Got an List of object List with several values per object, one of them is a "Text". I would like to seek which object have an especific text them get the index of the Object for the List.

to get index is not completed

var List = GetListObject();
var index = unitList.Select(x => x.Text.ToString().Contains("Text"));
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
Andres
  • 29
  • 3
  • Don't use Linq if you want performance. In your case, use a regular `for` loop as suggested in on of the answers. – l33t Sep 10 '20 at 20:03
  • I whole-heatedly agree - I can consistently write code faster than Linq. However, there are advantages, namely readability (if used in short chains) and job interviews. It looks like Andres is learning Linq - a skill that could land a sweet job later on. – Growling Pigeon Sep 11 '20 at 20:21

3 Answers3

2

check this

myLİst.Select((v, i) => new {Text = v, Index = i})
    .First(x=> x.Text.ToString().Contains("Text")).Index;
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
1

If you want to obtain index, I suggest good old for loop:

  int index = -1;

  for (int i = 0; i < List.Count; ++i)
    if (List[i].Text.Contains("Text")) {
      index = i;

      break;
    }

In case of Linq

  int index = List
    .Select((v, i) => new {v, i})
    .FirstOrDefault(pair => pair.v.Text.Contains("Text"))
   ?.i ?? -1;  

In both cases we get -1 if item with Text == "Text" is not found

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You can use Enumerable.Range(int, int).

For example: var zeroIndexes = Enumerable.Range(0, list.Count - 1).Where(x => list[x] == 0).ToArray() will give you an array of all indexes of list where the value is equal to zero.

So specific to your question, you can do:

int index = Enumerable.Range(0, unitList.Count - 1).Where(x => unitList[x].Text.ToString().Contains("Text")).FirstOrDefault();

This will give your the first index or 0 if not found.