leora
leora

Reputation: 196459

C# LINQ find where name is in list

i have a List of objects and i want to sort by a certain field and then find out what "rank" or index is a certain name.

for example, lets say i have a:

List<Location> Locations= new List<Location>();

and i want to sort by Popularity

var list = this.Locations.OrderBy(r => r.PopularityPct); 

i now want to find out what is the index of "Spain" (NOTE: "Spain" would be a lookup of the Name property, where Name would be a property of the location object) now that this list is sorted by popularity.

what is the easiest way of doing this?

Upvotes: 0

Views: 3122

Answers (3)

Ankur
Ankur

Reputation: 33637

You can do something like below:

public static int FindIndexOf(IEnumerable<Location> items,string val)
{
    int index = -1;
    items.Where((x, i) => {
                var ret = x.City == val;
                if (ret)
                    index = i;
                return ret;
            }).ToList();
    return index;
}

I know this is weird :)

Upvotes: 0

George Duckett
George Duckett

Reputation: 32428

First sort locations, then...

from index in Enumerable.Range(0, Locations.Count)
let r = Locations[index]
..WHERE CLAUSE
select index

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500165

You can easily get all of the names and indexes like this:

var list = this.Locations.OrderBy(r => r.PopularityPct)
                         .Select((value, index) => new { value, index });

Then, for example:

var spainIndex = list.Single(x => x.value.Name == "Spain").index;

Or print everything:

foreach (var pair in list)
{
    Console.WriteLine("{0}: {1}", pair.index, pair.value.Name);
}

This is assuming you want the post-sorted rank. If you want the index in the initial list, you'd switch the order:

var list = this.Locations.Select((value, index) => new { value, index });
                         .OrderBy(r => r.value.PopularityPct);

Upvotes: 6

Related Questions