joelg
joelg

Reputation: 367

Sort list index by value

I have a list in C#

List<int> temp = new List<int>(0, 1, 2, 3, 4, 2, 8);

And I would like to make a list of items in temp that satisfy a bool expression, such as

List<int> results = temp.Sort(x > 2);

But .Sort() doesn't exist. The resulting list results would then contain

(3, 4, 6)

Which are the indexes of the values in the original list temp that are greater than 2.

Sorry if this is trivial or has been asked before; I'm new to coding and to SO. Thanks!

EDIT: As some of you have correctly pointed out, I'm don't actually want to sort the list, I just want to filter it. Thanks!

Upvotes: 0

Views: 137

Answers (5)

Magnus
Magnus

Reputation: 46919

A simple, fast and easy to understand solution would be:

for (int i = 0; i < temp.Count; i++)
    if(temp[i] > 2) results.Add(i);

Upvotes: 2

Christos
Christos

Reputation: 53958

You could try this one:

List<int> results = temp.Select((x, index) => new { Index = index, Number = x })
                        .Where(x=>x.Number > 2)
                        .Select(x=>x.Index);

Upvotes: 0

Habib
Habib

Reputation: 223237

From the output it appears that you need Indices

List<int> temp = new List<int>{0, 1, 2, 3, 4, 2, 8};
var newList = temp.Select((r, i) => new { Index = i, Value = r })
                    .Where(r => r.Value > 2) //For your condition
                    .OrderBy(r => r.Value)
                    .Select(r => r.Index)   //For output
                    .ToList();

This would return you (3, 4, 6)

EDIT: Since the question has been edited and pointed out that sorting the list based on value is not required, in that case OrderBy in the above statement can be left out.

var newList = temp.Select((r, i) => new { Index = i, Value = r })
                    .Where(r => r.Value > 2) //For your condition
                    .Select(r => r.Index)   //For output
                    .ToList();

Upvotes: 4

Xiaoy312
Xiaoy312

Reputation: 14477

You need to keep store the index before applying the where clause, or it will be lost.

List<int> temp = new List<int>{ 0, 1, 2, 3, 4, 2, 8 };
List<int> results = temp.Select((x,i) => new { Value = x, Index = i })
                        .Where(x => x.Value > 2)
                        .Select(x => x.Index)
                        .ToList();

Upvotes: 0

D Stanley
D Stanley

Reputation: 152521

I would like to make a list of items in temp that satisfy a bool expression,

That would be Where:

List<int> temp = new List<int>(0, 1, 2, 3, 4, 2, 8);

List<int> results = temp.Where(x => x > 2);

There are many variations of Select and Where that include the index of items that meet a criteria - if you can be more clear on what you want then you will get better examples.

Upvotes: 0

Related Questions