Mc27 Mc27 - 25 days ago 15
C# Question

Get list items upto match in C#

I need a better solution for the below code in linq or any other better way, The code gets all items upto match condition.If the condition is process.Name = "process-5" it should return all items upto the condition match including the matched item in this case there will be 5 items in the list.

using System;
using System.Collections.Generic;

namespace ListSelectSample
{
class Process
{
public long Id { get; set; }

public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var processlist = new List<Process>();
for(var count = 1; count <= 10; count++)
processlist.Add(new Process() { Id = count, Name = "Process-" + count});

var selectedprocesslist = new List<Process>();

foreach (var process in processlist)
{
selectedprocesslist.Add(process);

if (process.Name.ToLower().Equals("process-4"))
break;
}
Console.ReadKey();
}
}
}

Answer

TakeWhile and SkipWhile should do the trick.

var selectedProcessList = processList
                          .TakeWhile(x => !x.Name.ToLower().Equals("process-4"))
                          .ToList();

// Include selected item
if (selectedProcessList.Length < processList.Length)
    selectedProcessList.Add(processList
                            .SkipWhile(x => !x.Name.ToLower().Equals("process-4"))
                            .First());

EDIT: With the above method's checks and caveats, a hybrid solution might be cleaner:

int idx = processList.Select(x => x.Name.ToLower()).ToList().IndexOf("process-4");
var selectedProcessList = idx < 0 ? processList : processList.Take(idx + 1).ToList();

Like M.kazem is saying, though, a LINQ solution won't be as efficient as the iterative method you are currently using. If your list is small enough, the difference is negligible, but keep that in mind.

Comments