简体   繁体   中英

how to Search List with Comma Separated values in c#

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM