-1

I'm trying to remove all items inside a list that contain a certain last name in c#.

I don't really have any code to show as I've just been researching how to do it and I can't find solutions anywhere.

Input with be in format of "First Last" I can't change that.

    List<string> people = new List<string>();
    people.Add("Tommy Chan");
    people.Add("Taylor Chan");
    List<string> contain = new List<string>();
    foreach (string s in people)
    {
        if (s.Contains("Chan"))
        {
            //Remove Item from list here
            Console.WriteLine("Removed");
        }
        else
        {
            Console.WriteLine("Doesn't Contain Chan");
        }
   }
   Console.ReadKey();

This is just needed for a project where it takes a list of peoples names and groups them by last name giving the ability to remove all with a certain last name. I can't seem to find anywhere where I can search an entire List by find a certain amount in the list. I've found lots of different loops but they all require it to exact match the entire string.

Thanks

Coderz
  • 215
  • 2
  • 7
  • 20
  • 4
    Create an object with `FirstName` and `LastName` properties. Make a list of that class instead of a list of strings. Populate the first/last name fields separately. This will make it far easier to filter and group. –  Sep 03 '19 at 18:30
  • The input is in "First Last" functions this is just a mockup to test the functionality. It must remove both the First and the Last Name together. based on last name. @Amy – Coderz Sep 03 '19 at 18:33
  • 2
    it should be "s.Contains" if (s.Contains("Chan")) – ssilas777 Sep 03 '19 at 18:33
  • @ssilas777 fixed it in my cod but question still remains – Coderz Sep 03 '19 at 18:36
  • people.RemoveAll(s => s.Contains("Chan")); are you looking for something like this? – ssilas777 Sep 03 '19 at 18:39
  • @Coderz My comment is still applicable. –  Sep 03 '19 at 18:39
  • Contains function won't work here, It would remove the string if "Chain" found anywhere, will not check if "Chain" is really a last name... s.EndsWith(" Chain") would be a good option. – Rashid Ali Sep 03 '19 at 18:42
  • 1
    Marked as duplicate but scope of the question is different than the one declared as duplicate to this... that question is about sub-string (anywhere in the string) that could be retrieved with string.Contains but this is about last word in the string where string.Contains won't really work! – Rashid Ali Sep 03 '19 at 18:49
  • @CodeCaster This isn't about finding elements that "contain" a string. It's about matching last names, while not matching to a first name. – Gabriel Luci Sep 03 '19 at 19:16

1 Answers1

1

I suggest using Linq:

var filteredList = people.Where(p => p.EndsWith(" Chan")).ToList();
Isitar
  • 1,286
  • 12
  • 29