将一个元素从列表复制到另一个(如果存在)
Copy an element from a list to another(if exists)
我想知道如何将特定元素从列表复制到另一个列表。
到目前为止,我有一个列表,其中包含一些“post”。
posts 有一些字段:_id, _postNumber, _dataOfCreation, _postTitle, _postDescription
.
我还创建了一个 bool 类型的方法,它负责根据 id 检查该列表中是否有 post。
所以目标是根据 ID 向我的控制台显示特定 post 的信息。
我的逻辑是:检查 post 是否存在(如果为真)将 post 复制到另一个列表并使用 foreach 循环显示整个信息(id,[=24= 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.
}
}
您首先需要找到post。
var specificPost = ListOfPosts.Where(post => post.Id == EnteredId).FirstOrDefault();
然后你可以用它做任何你想做的事,比如将它复制到另一个列表。
_anotherList.Add(specificPost);
我想知道如何将特定元素从列表复制到另一个列表。
到目前为止,我有一个列表,其中包含一些“post”。
posts 有一些字段:_id, _postNumber, _dataOfCreation, _postTitle, _postDescription
.
我还创建了一个 bool 类型的方法,它负责根据 id 检查该列表中是否有 post。
所以目标是根据 ID 向我的控制台显示特定 post 的信息。
我的逻辑是:检查 post 是否存在(如果为真)将 post 复制到另一个列表并使用 foreach 循环显示整个信息(id,[=24= 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.
}
}
您首先需要找到post。
var specificPost = ListOfPosts.Where(post => post.Id == EnteredId).FirstOrDefault();
然后你可以用它做任何你想做的事,比如将它复制到另一个列表。
_anotherList.Add(specificPost);