How to get a linq log in asp.net core?

0

I do the following query with linq, but I can not get that id that I retrieve in the query.

var seccionGrado = (from sg in _context.SeccionGrado
                                    where sg.IdSeccion == user.IdSeccion
                                    && sg.IdGrado == user.IdGrado
                                    select new
                                    {
                                        id = sg.IdSeccionGrado
                                    }).ToList();

var s = Convert.ToInt32(seccionGrado[0]);

    
asked by Karla Huerta 24.02.2018 в 00:50
source

1 answer

1

You are trying to convert an anonymous object to an integer.

You can use FirstOrDefault or SingleOrDefault to get a single item from the list resulting from the query, beware that this last method will throw an exception if there is more than one item that meets the criteria. Both will return the default value according to the type of data resulting, that in the case of a int is 0.

I'll give you an example with this last method.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    class SeccionGrado {
        public int Id;

        public SeccionGrado(int Id) {
            this.Id = Id;
        }
    }

    public static void Main()
    {
        List<SeccionGrado> grados = new List<SeccionGrado>();
        for(int i = 0; i <= 5; i++){
            grados.Add(new SeccionGrado(i));
        }

        int s = (from g in grados where g.Id == 3 select g.Id).SingleOrDefault();

        Console.WriteLine(s);
    }
}
    
answered by 24.02.2018 в 01:10