Tim Cooley
Tim Cooley

Reputation: 759

How do I make a multiple lists from one list?

I have a list of items that can have multiple criteria assign to it. They could be red, blue, green or red AND blue, blue AND green, red AND green or red AND blue AND green.

What I want to be able to do, at run time, is create the three lists.

I started with a class I can fill out

[System.Serializable]
public class Item
{
    public bool red;
    public bool blue;
    public bool green;
}

Made the list

public List<Item> itemList;

I am not sure how to make a redList, blueList and greenList.

I am pretty lost on this. I feel like I need to do a for loop through the first list that was made. Then check to see if the bool is true, if it is add it to the new list.

new List<Item> redList;

for (int i = 0; i < itemList.Count; i++)
    {
      if( red == true)
       {
            redList.Add();
       }
     }

Upvotes: 0

Views: 232

Answers (2)

Everts
Everts

Reputation: 10721

This may not answer the question but it could help someone getting here (or even you).

You should think about Flags:

[System.Serializable]
public class Item
{
    public ColorType colorType;
}
[Flags]
enum ColorType
{
    Red, Blue, Green
}

Then you have amn Editor Script to allow multiple choice in inspector:

[CustomPropertyDrawer(typeof(ColorType))]
public class IMovementControllerDrawer : PropertyDrawer
{
    public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
    {
        _property.intValue = EditorGUI.MaskField(_position, _label, _property.intValue, _property.enumNames);
    }
}

Finally you can use the colorType instance to check what it is:

if ((this.colorType & ColorType.Red) == ColorType.Red) { // It is Red}
if ((this.colorType & ColorType.Green) == ColorType.Green) { // It is Green}
if ((this.colorType & ColorType.Blue) == ColorType.Blue) { // It is Blue}

Notice the & that is NOT &&. This is performing some bit manipulation. It is then possible for your object to run 0, 1, 2 or all path in the if statements.

Upvotes: 2

mrinalmech
mrinalmech

Reputation: 2175

Your general idea is right. I am assuming once you have the ItemList you want to create three colored lists out of it. This is the code.

new List<Item> redList;

for (int i = 0; i < itemList.Count; i++)
    {
      if(itemList[i].red)
       {
            redList.Add(itemList[i]);
       }

     if(itemList[i].blue)
       {
            blueList.Add(itemList[i]);
       }

     if(itemList[i].green)
       {
            greenList.Add(itemList[i]);
       }
    }

At the end blueList,redList and greenList will have all the items with blue,red and green properties set to true. There will be overlaps as elements can have multiple colors set to true.

Upvotes: 2

Related Questions