mszabolcs
mszabolcs

Reputation: 67

Lambda expression and class method

I have a problem like this.

List<Absent> absent = new List<Absent>();
Console.WriteLine("--------------------------");
Console.Write("Please enter a full name> ");
string temp_str = Console.ReadLine();


absent.Where(x => x.Name == temp_str).Run(x = x.WriteConsoleTable());

How can I run a method after doing a filtering? Absent is a Class which has a Name variable and WriteConsoleTable method.

Upvotes: 0

Views: 82

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56453

Seems like you're looking for the ForEach extension method but you'll first need to call ToList on the IEnumerable sequence returned from the Where clause.

absent.Where(x => x.Name == temp_str)
      .ToList()
      .ForEach(x => x.WriteConsoleTable());

or you can iterate over the collection using the foreach construct.

i.e.

foreach (var item in absent.Where(x => x.Name == temp_str))
        item.WriteConsoleTable();

Upvotes: 2

touchofevil
touchofevil

Reputation: 613

You can try below options.

var absences = absent.Where(x => x.Name == temp_str);
foreach(var abs in absences)
{
    abs.WriteConsoleTable();
}

or if you are sure you only need first match

var absence = absent.FirstOrDefault(x => x.Name == temp_str);
if(absence != null)
{
    absence.WriteConsoleTable();
}

Upvotes: 0

Related Questions