Home > Software engineering >  how to Search List with Comma Separated values in c#
how to Search List with Comma Separated values in c#

Time:07-28

I have a list and want to find values in it. Search text to find the values will be in Comma separated string.

Input:

var students = new List<Student>() { 
                new Student(){ Id = 1, Name="One"},
                new Student(){ Id = 2, Name="Two"},
                new Student(){ Id = 3, Name="Three"},
                new Student(){ Id = 4, Name="Four"},
                new Student(){ Id = 5, Name="Five"}
            };

Search Text:

var searchString = "Two,Three";

Output:

{Id = 2, Name="Two"},
{Id = 3, Name="Three"}  

Thanks in Advance.

CodePudding user response:

First, I'd split the search string and put the values into a HashSet:

var searchValues = new HashSet<string>(searchString.Split(','));

Next, check if the elements match, for example using LINQ:

var filteredStudents = students.Where(s => searchValues.Contains(s.Name)).ToList();

CodePudding user response:

Well, standard loops, raw code, you have this;

        var students = new List<Student>() {
            new Student(){ Id = 1, Name="One"},
            new Student(){ Id = 2, Name="Two"},
            new Student(){ Id = 3, Name="Three"},
            new Student(){ Id = 4, Name="Four"},
            new Student(){ Id = 5, Name="Five"}
        };

        string searchString  = "Two, Three";

        searchString = searchString.Replace(" ", ""); // remove blanks

        foreach (Student OneStudent in students)
        {
            foreach (string OneSearchItem in searchString.Split(','))
            {
                if (OneStudent.Name == OneSearchItem)
                {
                    Debug.Print(OneStudent.Id.ToString()   " , "   OneStudent.Name);
                }
            }
        }

Not pretty - but shows looping, and how to pick apart each item.

Next up, a linq expression.

        List<Student> MyFoundList = new List<Student>();

        foreach (string OneSearchItem in searchString.Split(','))
        {
            List<Student> MyFind=
                 students.FindAll(mystudents => mystudents.Name.Equals(OneSearchItem));

            MyFoundList.AddRange(MyFind);
        }

        // display all results
        foreach (Student OneStudent in MyFoundList)
            Debug.Print(OneStudent.Id.ToString()   " , "   OneStudent.Name);

So, I would go with the 2nd.

I "think" there is a relative clean and readable way to pass the search part a "list", and thus even the for/each for the split on search terms could be dropped (would be happy if shown how this is possible).

However, I think the above is readable enough - and easy to adopt.

  • Related