0

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.

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I had some search before writing this post, but after Where there's no ForEach.
Ohh, yeah, I see. Working Perfectly. Thanks!
Right, if you're looking for only a single match then as the other answer has suggested you should utilise FirstOrDefault or even SingleOrDefault depending on your end goal.
0

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();
}

1 Comment

It looks like working. absent.FirstOrDefault(x => x.Name == temp_str).WriteConsoleTable(); I used like this, because I know there should be data. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.