How to extract results from Linq query?

class Program
{
    static void Main(string[] args)
    {
        MyDatabaseEntities entities = new MyDatabaseEntities();

        var result = from c in entities.Categories
                        join p in entities.Products on c.ID equals p.IDCategory
                        group p by c.Name into g
                        select new
                        {
                            Name = g.Key,
                            Count = g.Count()
                        };

        Console.WriteLine(result.ToString());
        Console.ReadLine();
    }
}

How can I extract values ​​from a result set so that I can work with them?

+3
source share
3 answers
foreach (var item in result)
{
    var name = item.Name;
    var count = item.Count;
    ...
}

This will only work inside the same method where the LINQ query is located, since the compiler only then finds out what properties are available in the anonymous object type ( new { }) used in your LINQ select.

If you return a LINQ query to the calling method and want to access it as shown above, you need to define an explicit type and use it in the LINQ query:

class NameCountType
{
    public string Name { get; set; }
    public int Count { get; set; }
}

...

return from ... in ...
       ...
       select new NameCountType
              {
                  Name = ...,
                  Count = ...,
              };
+11
source

For instance:

foreach (var x in result)
{
   Console.WriteLine(x.c.Name);
}
0
source
 var results = (from myRow in ds.Tables[0].AsEnumerable()
                  where myRow.Field<String>("UserName") == "XXX"
                  select myRow).Distinct();
 foreach (DataRow dr in results)
    UserList += " , "+dr[0].ToString();
0
source

Source: https://habr.com/ru/post/1762296/


All Articles