Answer the question
In order to leave comments, you need to log in
How can I implement this in a List?
My project has: (This is a test code)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class TestEvent
{
public int b;
}
public class TestScript : MonoBehaviour
{
public List<TestEvent> testEvents;
private int a = 3;
private void Start()
{
}
}
Answer the question
In order to leave comments, you need to log in
Only here it is necessary to use LINQ with care. Personally, I would not use it at all in the same Update or any other place where the code is often called.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[System.Serializable]
public class TestEvent
{
[SerializeField] private int _b;
public int B => _b;
}
public class TestScript : MonoBehaviour
{
[SerializeField] private List<TestEvent> _testEvents;
private int a = 3;
void Start()
{
var events = _testEvents
.Where(item => item.B == a)
.ToArray();
}
}
public class TestScript : MonoBehaviour
{
[SerializeField] private List<TestEvent> _testEvents;
private int a = 3;
void Start()
{
var events = GetEvents(_testEvents, item => item.B == a);
}
private static List<TestEvent> GetEvents(
IEnumerable<TestEvent> testEvents, Func<TestEvent, bool> predicate)
{
var results = new List<TestEvent>();
foreach (var item in testEvents)
{
if (predicate(item))
{
results.Add(item);
}
}
return results;
}
}
public class TestScript : MonoBehaviour
{
[SerializeField] private List<TestEvent> _testEvents;
private int a = 3;
void Start()
{
var element = GetFirstOrDefault(_testEvents, item => item.B == a);
if (element is not null)
{
c = element.c;
r = element.r;
u = element.u;
}
}
// Если совпадение не найдено, то вернуть значение по умолчанию.
private static T GetFirstOrDefault<T>(IEnumerable<T> items, Func<T, bool> predicate)
{
foreach (var item in items)
{
if (predicate(item))
{
return item;
}
}
return default;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question