I have an array of type Brick
with each brick
having an isBroken
bool
property. How can I use Linq
to filter all bricks with isBroken = true
into a new array?

- 471
- 5
- 14
-
Have you tried this? : `BrickList.Where(x=> x.isBroken).ToList();` – sujith karivelil Jul 07 '17 at 10:59
-
@un-lucky that would be `.ToArray()` but yes you're right :) – EpicKip Jul 07 '17 at 11:33
3 Answers
Use Where
to filter the list of bricks and ToArray
to materialize the result into a new array.
var result = MyBricksArray.Where(x => x.isBroken).ToArray();

- 133,658
- 13
- 134
- 193
-
This will indeed create a new array, but the reference to the objects in the the array would stay the same. https://stackoverflow.com/questions/2774099/tolist-does-it-create-a-new-list – GaelSa Jul 07 '17 at 13:23
I hope this example will explain things more clearly, Let the definition of your class will be like the following:
public class Brick
{
public string Name;
public bool isBroken ;
}
And the Array of it's objects is defined like this:
Brick[] BrickArray =new Brick[]{
new Brick(){Name="A",isBroken=true},
new Brick(){Name="B",isBroken=true},
new Brick(){Name="C",isBroken=false}};
Then you can use the .Where
to filter the collection like the following:
var selectedBriks = BrickArray.Where(x=>x.isBroken).ToList();
Now the selectedBriks
will contains the items with name A
and B

- 28,671
- 6
- 55
- 88
You can use the select method for this :
var theNewList = Brick.Where(b => b.isBroken).Select(b => new Brick
{
//Populate new object
}).ToList() / .ToArray();
Note that Select is used and not where to project the List into a new one.
Also, the .ToList()/ToArray() is to add the array to memory, you may not need it, .Select() return an IEnumerable.
It is possible to use Brik.Where(..).ToList(); as this would create a new List but the reference to the object inside the list would be the same, so again it depands on your need.
And .Select() require using System.Linq;

- 580
- 4
- 10
-
Well, to illustrate and add to your answer, that if you want your Bricks to be copy of your initial bricks (in this case) and not the orignal Brick you have to instanciate new one, it seemed important to me because that's a big difference between instanciating a new list and create a list of new objects – GaelSa Jul 07 '17 at 15:16