Click here to Skip to main content
15,889,651 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I write a code for Classes i saved the data in the list of user defined type in which i want to delete the data from the user defined type list so if the list contains the data then it will remove it from the list so i use the function of list that is Contain but in contain function it only accept the string data
Plz tell me how should i convert the user defined list to the string list. Then i can check the following data is avaible or not then it will delete it from th


What I have tried:

public void remove_item(List<Male_zone>mens, Male_zone m)
       {
             List<string> asobj = new List<string>();

             asobj = mens.Cast<string>().ToList();

           if (asobj.Contains(m.m_item))
               {
                   asobj.Remove(m.m_item);
                   Console.WriteLine("Successfully delete");

               }
           else
           {
               Console.WriteLine("Not Found");
           }

       }

Main Function

Male_zone mens121 = new Male_zone();
Console.WriteLine("Please Enter the name of the item");

 mens121.m_item = Console.ReadLine();
mens121.remove_item(male_outlet, mens121);
Posted
Updated 11-Oct-19 20:20pm

1 solution

Your code is rather confused:
You don't actually remove anything from the list you pass in - because the Cast operation creates a copy of the original, not provides access to to the original under a different type.
Casting a list of objects doesn't use the contents of the objects and return the first string, it returns the object as a string - which means the object must implement an explicit casting operator.
Even if it did convert it to the "right string", it would be a list of strings, which wouldn't allow you to remove the item from the original collection!
Try this:
private bool RemoveItem(List<Male_zone> mens, Male_zone m)
    {
    Male_zone found = mens.FirstOrDefault(i => i.m_item == m.m_item);
    if (found != null)
        {
        mens.Remove(found);
        return true;
        }
    return false;
    }
And please, use standard naming conventions - no underscores, CamelCase, no "m_" prefix on members,... Whatever you are using is outdated: it's very old C++ format which predates C#, and that has been available since 2002 ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900