1

I want to display strings in a file that begins with the letter "F" (var target = "F";) and then print it in footlockerExistingBlogTextBox however only display 5 strings/lines. The file that holds the array contains more that 5 strings that begin with "F" and so I only want to display the last 5 latest entries. Thanks for your help in advance. Much appreciated.

Below displays my code:

var target = "F";
var results = footlockerArray.Where(r => r.StartsWith(target)).Reverse();

foreach (string result in results)
{
    footlockerExistingBlogTextBox.Text += result;
}

for (int i = footlockerArray.Length - 1; i > footlockerArray.Length - 5; i--)
{
    footlockerArray.Reverse();
    footlockerExistingBlogTextBox.Text += footlockerArray[i];
}
0

2 Answers 2

2

Use Enumerable.Take and you can get the results like:

var results = footlockerArray.Where(r => r.StartsWith(target))
                             .OrderByDescending(r=> r)
                             .Take(5);

Then to get a string separated by a new line you can use string.Join like:

footlockerExistingBlogTextBox.Text = string.Join(Environment.NewLine, results);
Sign up to request clarification or add additional context in comments.

3 Comments

You should order by descending before you take 5. Otherwise you are taking the top 5 and reversing them.
Additionally, you're still ordered wrong. They should be reversed again later on. Now you're taking the last 5 but they are still in reverse order. I'm not sure ordering them is correct because the OP never said they were in order - just that the last 5 are requested.
@Paul, yes now I see the OP has tried Reverse twice, If op needs an ascending order then another OrderBy(r=> r) could be add in the end of statement. I will leave that for OP.
1

Reverse and use Take(5):

     footlockerArray
        .Where(o => o.StartsWith("F"))
        .Reverse()
        .Take(5)
        .Reverse()
        .ToList()
        .ForEach(o => footlockerExistingBlogTextBox.Text += o);

Comments

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.