locked
FirstOrDefault doesnt work RRS feed

  • Question

  • User-2120563976 posted

    Hey ive got problem with getting TOP 1 element of my list. I use linq to generate somedata:

    var result = Emps.Where(emp => emp.Job == "Frontend programmer").OrderByDescending(emp => emp.HireDate).ToList();

    result returns 3 emps

    but when i try return top1 by make something like this

    result.FirstOrDefault();

    ive got nothing.

    Wednesday, May 20, 2015 10:49 AM

Answers

  • User281315223 posted

    No problem, if you only want this single item to appear within your list, just instantiate a list and populate it with your single employee :

    // Get the first single employee that matches your constraint.
    var employee = Emps.OrderByDescending(e => e.HireDate).FirstOrDefault(e => e.Job == "Frontend programmer");
    
    // Populate your data source
    ResultsDataGridView.DataSource = new List<YourEmployeeClass>() { employee };

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 20, 2015 12:04 PM

All replies

  • User281315223 posted

    You could actually just do something like this :

    // Get the first single employee that matches your constraint.
    var result = Emps.OrderByDescending(e => e.HireDate).FirstOrDefault(e => e.Job == "Frontend programmer");

    Wednesday, May 20, 2015 11:39 AM
  • User-2120563976 posted

    thank you but i have one more issue to fix. I must convert this to list because of

    ResultsDataGridView.DataSource = result;

    datasource accept list 

    toList() on result doesnt work.

    Wednesday, May 20, 2015 12:02 PM
  • User281315223 posted

    No problem, if you only want this single item to appear within your list, just instantiate a list and populate it with your single employee :

    // Get the first single employee that matches your constraint.
    var employee = Emps.OrderByDescending(e => e.HireDate).FirstOrDefault(e => e.Job == "Frontend programmer");
    
    // Populate your data source
    ResultsDataGridView.DataSource = new List<YourEmployeeClass>() { employee };

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 20, 2015 12:04 PM
  • User-2120563976 posted

    ye it was so simple thanks !

    Wednesday, May 20, 2015 12:07 PM