- Home /
Linq , lambda
Hi I have Generic GameObjects List of 10 items with different tags. I want to select two objects with "tag1", three with "tag2" and for example 1 GameObject with tag "tag3". I can do this :
var level1 = _allFigures.Where(go => go.tag == "BFig").Take(2).Select(go => go).ToList();
but how to add more different figures with different tag to one list ? It don't have to be in one line of course. I think I should use SelectMany ? I'am not sure
EDIT: I end up with something like this... Is there a better solution ?
_figuresLevel1 = _figuresLevel1.Concat(TakeFigures(_allFigures, 2, "RFig")).
Concat(TakeFigures(_allFigures, 2, "BFig")).
Concat(TakeFigures(_allFigures,2,"YFig")).ToList();
List <GameObjects> TakeFigures(List<GameObjects> figures, int figCount, string nameOfFigures)
{
return figures.Where(go => go.tag == nameOfFigures).Take(figCount).Select(go =>go).ToList();
}
List "GameObjects" of course but editor is removing this "<"
First, you don't need the Select portion (you're just doing the default select of the entire object, not a portion of it). So skip that.
Depends on what you want to do. You can select all items with the tags you want quite easily (just make a list of the tags you want and use that in the query), but it looks like you only want to select the fist X of one type Y of another etc (hence the take statement and you saying 2 of this 3 of that etc). Is that a requirement? If you wanted to take the same number from each tag you could probably wrap it all in one.
What in effect are you trying to do? I know no one ever wants to give up their game idea (and so are as ambiguous as possible) but could you be a little more detailed about what your list is and why you are trying to filter it this way? $$anonymous$$aybe this isn't the best approach.
Another option would be to do this in a loop and have a Dictionary that has the tags you want and how many of each.. but that seems overkill.
List<go> TakeFigures(Dictionary<string,int> tagAndAmounts, figures)
{
List<go> filteredFigures = new List<go>();
foreach( var kvp in tagAndAmounts)
{
var items = figures.Where(go => go.tag == nameOfFigures).Take(figCount).ToList();
if(items!=null) filteredFigures.AddRange(items);
}
}
Not sure that's any better though.
Hi dubbreak, thank you very much , I forgot about dictionary , I guess list of tag's it's a good idea too.
Glad to help. Yeah if you didn't have to use take to grab only a few of each then you could have a nice one liner with a list of tags.
Your answer

Follow this Question
Related Questions
How to shortcut a lambda expression through a function? 1 Answer
C# Finding Closest Instance LINQ Error 1 Answer
Problem with using Linq: Operation is not valid due to the current state of the object 1 Answer
Unity doesn't recognize "List" object type (Linq) 2 Answers
External mapping in Unity ? 1 Answer