0

In my application, I have a List<float[]> with arrays varying in sizes each time the application runs. I want to find out the index of arrays in that List<float[]> with length less than or equal to a specified value.

Lets say I have a List [ float[100], float[80], float[101] ]. Now I want to know the indexes of those arrays whose length is less than or equal to 100.

I can create Loop and Iterate through each element in the list but that way seems too long. Is there any LINQ way possible?

6
  • 1
    You would not need to iterate through each array, you could use the Length property. Commented Jun 23, 2021 at 20:27
  • You can get indices using Linq, but it requires a lookup table iirc. A simple for loop seems like a fine way to go. Commented Jun 23, 2021 at 20:31
  • @hijinxbassist I was saying the same thing that I can go through each element in the List and use the length property to filter out the arrays that are satisfying the length condition. Commented Jun 24, 2021 at 2:25
  • but I really don't get why my question gets a downvote. Commented Jun 24, 2021 at 2:25
  • @hijinxbassist: What exactly do you mean by "a lookup table" here? A natural LINQ query would just iterate over the list. Commented Jun 24, 2021 at 5:37

1 Answer 1

3

You could use Linq's Select to get the indexes, and Where to filter them out:

List<int> indexes = list.Select((arr, ind) => (arr, ind))
                        .Where(x => x.arr.Length <= 100)
                        .Select(x => x.ind)
                        .ToList();
Sign up to request clarification or add additional context in comments.

9 Comments

OP wants to kwow indexes of filtered items, if I'm not wrong. Maybe he asked the wrong question, I don't know...
@Marco I completely misread the question somehow... Edited and fixed.
@Marco Yes exactly, I wanted to know the index of those arrays that are satisfying the length constraint.
@Mureinik thank you for reply, but I am unable to compile the code as it is showing an error on the first Select statement which says, "A local variable named 'arr' cannot be declared in this scope because it would give a different meaning to 'arr', which is already used in a 'parent or current' scope to denote something else"
@abhinavp650: new { arr, ind } uses an anonymous type, which is a class - so it's creating a new object for each element in the array. (arr, ind) is a ValueTuple, which is a value type - no new objects being created. The new objects for the anonymous type version will be short-lived, so the performance difference may very well not be significant... it's just worth being aware of the difference.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.