Marc Rasmussen
Marc Rasmussen

Reputation: 20545

C# find object in list using a object field

So i have the following List:

List<AttackStyle> AttackStyles = new List<AttackStyle>();

With the following types of objects:

AttackStyle lStyle = new AttackStyle();
lStyle.Name = "Attack Achilles";
lStyle.ParameterID = 0;
lStyle.Forward = Vector3.forward;
lStyle.HorizontalFOA = 70f;
lStyle.VerticalFOA = 40f;
lStyle.DamageModifier = 1f;
lStyle.ActionStyleAlias = "Jump";
lStyle.IsInterruptible = true;

AttackStyles.Add(lStyle);

Now i wish to find the field ParameterID where the ActionStyleAlias is equal to a value (for instance "Jump")

This is for a Unity application so the search / find needs to be as fast as possible.

Upvotes: 0

Views: 87

Answers (5)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Let's return first ParameterID if there's the required item in the collection; -1 otherwise:

 var result = AttackStyles
   .Where(item => item.ActionStyleAlias == "Jump")
   .Select(item => item.ParameterID)
   .DefaultIfEmpty(-1)
   .First();

Upvotes: 1

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

You can try extension methods. Also you should consider null cases:

static class Extensions
{
    public static int? FindParameterId(this List<AttackStyle> values, string actionStyleAlias)
    {
        return values.FirstOrDefault(x => x.ActionStyleAlias == actionStyleAlias)?.ParameterID;
    }
}

Then use it:

List<AttackStyle> attackStyles = new List<AttackStyle>();
var parameterId = attackStyles.FindParameterId("Jump");

Upvotes: 0

OmG
OmG

Reputation: 18838

The straight solution is:

 var pId = AttackStyles.FirstOrDefault(x=> x.ActionStyleAlias == "Jump")?.ParameterID

But if you want to get a better performance, it would be better, to index the most useful property which you want. Therefore, construct a dictionary on the most useful fields to get a better performance in time. For example:

   var styles = new Dictionary<string, AttackStyle>();
   styles.Add("Jump", new AttackStyle() 
                      {
                           Name = "Attack Achilles",
                           ParameterID = 0,
                           Forward = Vector3.forward,
                           HorizontalFOA = 70f,
                           VerticalFOA = 40f,
                           DamageModifier = 1f,
                           ActionStyleAlias = "Jump",
                           IsInterruptible = true
                      });

Then, find the object by this:

var pId = styles["Jump"].ParamterId;

or if it might be null:

if(styles.Keys.Contains("Jump"))
    var pId = styles["Jump"].ParamterId;

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222522

var result = AttackStyles.FirstOrDefault(x => x.ActionStyleAlias == "Jump").ParameterID;

Upvotes: 3

Guilherme
Guilherme

Reputation: 5341

var param = AttackStyles.First(x => x.ActionStyleAlias.Equals(value)).ParameterID;

Upvotes: 1

Related Questions