Find Something in List of Objects, where object value is equal to string

c# entity-framework-core linq

Question

My classes

public class User
{
    [Key]
    public long Id {get;set;}
    public ICollection<AuthToken> Tokens { get; set; } = new List<AuthToken>();
}

public class AuthToken
{
    [Key]
    public long id { get; set; }
    public string Token { get; set; }
    public long Created { get; set; }
    public long Dispose { get; set; }
    public string Ip { get; set; }
    public string LocalisationInfo { get; set; }
    public string MachineInfo { get; set; }
}

I want to select AuthToken object, which string Token is equal to

123 `

var user = cnx._Users
              .Where(x => x.Tokens.Contains(/*Tokens.Token object equal to 123 */))

In simply Where condition I can only compare two AuthToken objects. I need to compare AuthToken.Token strings.

Finally I want to select User who has Token I used. In this case its 123.

1
0
2/12/2020 1:40:14 PM

Accepted Answer

You can 'chain' multiple linq calls to get the result you want...

var user = cnx._Users.Where(u => u.Tokens.Any(atoken => atoken.Token == "123")).FirstOrDefault();
4
2/12/2020 1:44:51 PM

Popular Answer

You can also achieve it like below

var user = cnx._Users.Where(x => x.Tokens.FirstOrDefault(t => t.Token == "123") != null);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow