Reputation: 3759
I have a class holding a Color
and a string:
public class Magic{
public string Name {get; set;}
public Color MyColor {get; set;}
}
I have a List of them:
List<Magic> MyList = new List<Magic>();
I'm not too experienced with LINQ and I want to know how to get all Color
objects in the List
into a new List
of just the Color
s
Upvotes: 2
Views: 3733
Reputation: 814
I used the .FindAll approach.
var lst = GetAllProducts();
List<ProductModel> sel = lst.FindAll(x => x.IsActive == true);
return sel;
I have a method that gets all the products into a List<>. My Product Model has a property called IsActive (a boolean).
This code creates a new List<> of just the Active=True products.
Upvotes: 0
Reputation: 4651
The question is a bit vague, and if you are looking for a projection of colors, then @ChrisSinclair answer is correct.
If, on the other hand, you want to filter by color, then you can do it like this:
var magicS = (from magic in MyList where magic.MyColor == s select magic).ToList();
or
var magicS = MyList.Where(m => m.MyColor == s).ToList();
Upvotes: 1
Reputation: 23208
You would use the Select method:
List<Color> magicColors = MyList
.Select(magic => magic.MyColor)
.ToList();
If you want only the unique colours:
List<Color> magicColors = MyList
.Select(magic => magic.MyColor)
.Distinct()
.ToList();
The idea is that for every Magic
, it will pull out its MyColor
. That's what the Select(magic => magic.MyColor)
does.
Upvotes: 6