Share via

help with a system linq method - IEnumerable Where

Hacking 81 Reputation points
2022-06-15T08:27:11.67+00:00

I have this line of code:
writer.Write(String.Join(Environment.NewLine, File.ReadAllLines(file).Where<string>((line) => line.ToLower().Contains(textToSearch.ToLower()))));
and the writer is a StreamWriter.

The function is to write to a file only the lines of another file which contains a specific string but i want to add to each line another string.
Example: the line matched is "c:\sura\da\k.txt" and i want to add "(from k.txt)" as example.

Is that possible?

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Bruce (SqlWork.com) 84,086 Reputation points
2022-06-15T15:20:16.507+00:00

Just add a select, which is the linq map function

writer.Write(String.Join(Environment.NewLine,   
         File.ReadAllLines(file)  
               .Where<string>(line => line..Contains(textToSearch, StringComparison.OrdinalIgnoreCase)  
                .Select( line => line + $” (from {textToSearch})”)   
)));  

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,606 Reputation points Volunteer Moderator
    2022-06-15T09:20:25.927+00:00

    Of course it is possible but would advise against a one-liner which maybe appealing but can't be debugged.

    • Break the code down using conventional foreach or for.
    • Rather than .ToLower use String.Contains(String, StringComparison) for .NET Core

    Going this path is not elegant but is easy to debug and write unit test methods.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.