Check if Exists and if so, Add it to Other List

Hi there! I’ve just experienced an odd issue and I’d like to be enlightened on this topic.

I’m posting a piece of code in which I’m inside a switch, but that’s not so important; what matters is that ** I’d like to check if in the list called mirror exists one object with a certain value and if so, add it immediately to a second list called Lpositions**.

Since I’m already checking if something like that exists it would be awesome to be able to just address that " x" and say: Lpositions.Add(x.position)! but that returns an error… how sad.

Could you help me?

I’m self-teaching me C# so if you could elaborate a bit your answer or pass me a link of not-too-complicated code I’d really appreciate.

Thanks for your time!

//Check if something other than rand is empty in our mirror list
			case 2:

				//hypotheticalActorsOnPoint is the value I want to check 
				if(mirror.Exists(x => x.hypotheticalActorsOnPoint == 0)){
					
					for(int j = 0; j < mirror.Count; j++){
						
						if(mirror[j].hypotheticalActorsOnPoint == 0){
							
							Lpositions.Add(mirror[j].position);
							mirror[j].hypotheticalActorsOnPoint++;
							i++;				//this code is inside a while loop too
							
							if(mirror[j].isFull){
								
								mirror.Remove(mirror[j]);
							}
							
							break;
						}
					}

					break;
				}

				else{

					goto default;
				}

Instead of using Exists, you could use Find. Something like this:

case 2:
   var t = mirror.Find(x => x.hypotheticalActorsOnPoint==0);
   if (t!=null)
   {
       Lpositions.Add(t.position);
       ...
   }

Your question about why you can’t use ‘x’ inside your if statement is bit more complex though. What C# lambda syntax means in your case goes roughly like follows:

The statement below is actually instruction to compiler to generate an anonymous method which takes in one parameter of type x and returns boolean.

x => x.hypotheticalActorsOnPoint == 0

if you had a method with signature:
bool MyComparer(T elementInList)

where T is the type of your object stored in list, you could write your if statement like this:

if(MyComparer)
{

}

If you check the msdn documentation for example the Find method I proposed you could use, it’s signature is like:

public T Find(
Predicate match
)

And as it happens the Exists method has exactly the same signature:

public bool Exists(
Predicate match
)

So keep in mind that whenever you are writing a lambda expression, you are actually declaring a method.

Hope this clarifies things a bit for you.