Search code examples
c#.netlistcopylogic

Copy an element from a list to another(if exists)


i would like to know how i can copy a specific element from a list to another.

I have a list so far with some "posts". that posts have some fields: _id, _postNumber, _dataOfCreation, _postTitle, _postDescription.

Also i have create a Method of type bool which is responsimple to check if there is a post in that list based on id.

So the goal is to display to my console the infos of a specific post based on ID.

And my logic says: check if the post exist(if true) copy that post to another list and use a foreach loop to display the whole info(id, postnumber, dateOfCreation, title, description) of that post.

  public static void DisplaySpecificPost(List<PostCore> listOfPosts)
    {
        Console.Clear();
        Console.WriteLine("Total Posts: {0}", listOfPosts.Count() + "\n");

        foreach (var post in listOfPosts)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Post ID : {0}", post.Id + "\n");
            Console.ResetColor();
        }

        Console.Write("Insert the ID:");
        var idForSigleDisplay = Convert.ToInt32(Console.ReadLine());

        var IdProtection = new IdProtections();
        var checkIDexistance = IdProtection.IdExistanceChecker(idForSigleDisplay);

        if (checkIDexistance == true)
        {
            //Logic.
        }
    }

Solution

  • You first need to find the post.

    var specificPost = ListOfPosts.Where(post => post.Id == EnteredId).FirstOrDefault();
    

    Then you can do what you want with it, like copying it to another list.

    _anotherList.Add(specificPost);