0

I have an array of integers:

int[] numbers = { 1, 3, 5, 7, 9 };

I also have an array of a custom object that contains an integer. I want to filter the array of custom objects using Lambda to only those matching integers in the numbers array above.

public class SomeStruct
{
    public int MyNumber;
}

ArrayOfSomeStruct = ArrayOfSomeStruct
    .Where(m = m.MyNumber is contained in numbers array);

How is this done?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
rwkiii
  • 5,716
  • 18
  • 65
  • 114

2 Answers2

3

Following your example, I've created an example here

This is the code that would get the elements of your array if their number is contained within your "number" variable.

ArrayOfSomeStruct = ArrayOfSomeStruct.Where(x => numbers.Contains(x.MyNumber)).ToArray();
Pietro Nadalini
  • 1,722
  • 3
  • 13
  • 32
3

Seems like you want something like that:

int[] numbers = { 1, 3, 5, 7, 9 };
var numbersSet = numbers.ToHashset(); // for performance reason
var filtered = arrayOfSomeStruct.Where(e => numbersSet.Contains(e.MyNumber));
Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111