0

It is hard to explain my problem writing it in "normal" language so I'll just post my code (it would be easier to understand):

I have my class File:

public class File
{
    public string Url { get; set; }
    public string Name { get; set; }
    public string Date { get; set; }
    public Bitmap Bitmap { get; set; }
}

So I created a list of files:

var files = new List<File>();

and, I have populated it with data.

Now I have a string (and only that.) I would like to find the index of the element containing that string in my list.

Something like:

int index = files.IndexOf(new File
        {
            string.Empty,
            myString,
            string.Empty,
            null
        });

Any idea?

Jodrell
  • 34,946
  • 5
  • 87
  • 124
Oiproks
  • 764
  • 1
  • 9
  • 34

4 Answers4

6

The List class has a method called FindIndex, that takes a Predicate<T> as a parameter.

You can use it like this:

var index = files.FindIndex(f => f.Name == myString);

It will return the index of the first element that matches the predicate or -1 if no such element was found.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

I guess you want to find the index of the first element with the Name property equals to myString variale:

var index = files.IndexOf(files.Where(x => x.Name == myString).FirstOrDefault());

Or even more simpler way:

var index = files.IndexOf(files.FirstOrDefault(x => x.Name == myString));`

Both return -1 if no such element was found.

Dmitry Stepanov
  • 2,776
  • 8
  • 29
  • 45
0

Firstly, I find all instances with Name containing the myString, then, use IndexOf to find his index in the list. The result is a collection index of the instances

var indexs = files.Where(f => f.Name.Contains(myString)).Select(ft=> files.IndexOf(ft));
Antoine V
  • 6,998
  • 2
  • 11
  • 34
0

Why not just use a foreach loop like

int pos = -1;
foreach(File file in files)
{
  pos++;
  if(file.Name == "string")
    break;
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • because `FindIndex` does the same with just one line of code, with the same efficiency? Also, you should initialize `pos` at -1, otherwise, you'll get a false positive if the file was not found. – Zohar Peled Nov 13 '18 at 09:34
  • @ZoharPeled setting `pos = -1` is correct .. Thanks – Rahul Nov 13 '18 at 09:35