ptuga
ptuga

Reputation: 69

List.Find using a struct list

I'm struggling with this specific topic. I have a list of struct element which I need to use as argument in a method.

public struct MyStruct
{

    public string F1;
    public string F2;

}

List<MyStruct> NewList = new List<MyStruct>();
NewList.Add(new MyStruct { F1 = "AAA", F2 = "BBB" });
NewList.Add(new MyStruct { F1 = "CCC", F2 = "DDD" });

If I try to find on item of that list using LINQ I can use: var Element = NewList.Find(x => x.F1 == "AAA");

but Element returns something I cannot convert to a list? I can use Element.F1 or Element.F2 but if I need to pass the Element itself to a method how should I do it? Also, if I try to define Element as:

List<MyStruct> Element = NewList.Find(x => x.F1 == "AAA");

It fails! But why? Isn't Element of that structure? .Find searches for an element which are 2 strings defined in the struct fields F1 and F2.

If I use .FindAll the error seems to go away on the definition List<MyStruct> Element? How can I define one single Element for NewList?

Can someone help me?

Thanks in advance

Upvotes: 0

Views: 2675

Answers (1)

P&#233;ter Csajtai
P&#233;ter Csajtai

Reputation: 898

List<T>.Find returns with a single element and not with a List<T>. You should declare your Element variable as MyStruct:

MyStruct Element = NewList.Find(x => x.F1 == "AAA");

You should also think about that Find returns the default value of the type you store in your list when it couldn't find a matching value.

Upvotes: 1

Related Questions