Wrong Linq expression when avoiding repetitions on a List

Asked

Viewed 75 times

3

I’m trying to avoid duplicate data before giving a set value. I have a class Player that has itself a property called NickName, this class is inserted in List.

Player class:

public class Player
{
    public string NickName { get; set; }
}

On the part of set, I need to insert everything into the variable player, where there is no player.NickName.

Metodo get and set:

public List<Player> player = new List<Player>();

public List<Player> Player
{
   get { return player; }
   set { player = value.Where(x => !player.Contains(x.NickName)); }
}

The above model gives error saying that it is not possible to convert string for Player. How can I do it the right way?

1 answer

3


The code is confused and seems to have conceptual errors, but I believe you want this:

set { player = value.Where(x => !player.Any(y => x.NickName.Contains(y.NickName))).ToList(); }

I put in the Github for future reference.

You have to scan item by item from the list to then see if the name matches, so you have to use one Any(). I cannot guarantee that it gives the desired result because the question is not as clear as the criteria, but at least it solves the error that existed. When LINQ seems difficult to do manually it is faster and simpler. The LINQ should only be used to facilitate, when it complicates it is not worth it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.