Search code examples
c#refactoring

refactor the big lists


I HAVE About twenty lists in a class like below

public class Storepart : MonoBehaviour
{
    public List<GameObject> A;

    public List<GameObject> B;
}

and I need to save a special index in each one, is there a way to refactor it?

public savedata() {

    for (int i = 0; i < Storepart.A.Count; i++) {
        if (Storepart.A[i].activeSelf) {
            SaveAindex = i;
        }
    }

    for (int i = 0; i < Storepart.B.Count; i++) {
        if (Storepart.B[i].activeSelf) {
            SaveBindex = i;
        }
    }
}

Solution

  • You can try a simple LINQ aproach here.

    using System.Linq;
    
    SaveAindex = Storepart.A.IndexOf(Storepart.A.LastOrDefault(gameObject => gameObject.activeSelf));
    

    This expression consists of 2 parts. The inner call to LastOrDefault traverses your List and returns the last element where the activeSelf is true. The outer call gets the index of the element found by LastOrDefault.

    Remarks:

    • If you are looking for the first element in your List<GameObject where activeSelf? is true use FirstOrDefault
    • The result of this LINQ expresion will be 0 if no element is found.