簡體   English   中英

如何在 c# 條件下從 object 列表中刪除所有下一個元素

[英]How to remove all next elements from list of object on condition in c#

我有一個對象列表

public class Card
{
    public int Id { get; set; }
    public double Price { get; set; }
    public string Name{ get; set; }
}

當條件匹配時如何從列表中刪除所有下一個元素 -

if(object1.Price== 0)
{
  //remove all next elements from list
}

我想將列表從 0 保持到匹配 position 就像如果價格在索引 5 處為零,則取 0 到 5 個元素。

您可以使用TakeWhileSelect的組合,例如:

var lst = new List<Card>()      {
     new Card() { Price = 2 },
     new Card() { Price = 1 },
     new Card() { Price = 0 },
     new Card() { Price = -1 },
     new Card() { Price = -2 },         
};
var found = false;      
var items = lst.TakeWhile(x => !found).Select(x => 
{
    if (x.Price == 0)
        found = true;
    return x;
});

這導致價格為 2、1、0 的項目被保留,而 -1 和 -2 被刪除。

請參閱此小提琴進行測試。

如果您使用List<T>其中TCard您可以使用List<T>.FindIndex來獲取與謂詞匹配的第一個元素的索引並獲取列表的范圍:

List<Card> cards = new List<Card> { new Card {Id = 1, Price = 1.0, Name = "Ace" }, 
new Card {Id = 2, Price = 0.0, Name="Two" }};
Predicate<Card> test1 = a => a.Price == 1.0;
Predicate<Card> test2 = b => b.Price == 0.0;
//You can also do something like this:
Predicate<Card> test3 = c => c.Price == 1.0 && c.Id == 1;


Console.WriteLine(GetCardRange(cards, test1).Count); //Prints 1
Console.WriteLine(GetCardRange(cards, test2).Count); //Prints 2
Console.WriteLine(GetCardRange(cards, test3).Count); //Prints 1

//or shorthand without declaring a Predicate:
Console.WriteLine(GetCardRange(cards, (a) => a.Price == 0.0).Count); //Prints 2


//Method accepts a predicate so you can pass in different
//types of condition(s)
public List<Card> GetCardRange(List<Card> cards, Predicate<Card> p)
{
    int index = cards.FindIndex(p);
    //if no card is found, either return the whole list 
    //or change to return null or empty list
    return index == -1 ? cards : 
       cards.GetRange(0, index + 1);
}

public class Card
{
    public int Id { get; set; }
    public double Price { get; set; }
    public string Name{ get; set; }
} 

如何顯示列表中的所有所需元素<object>到控制台 (C#)<div id="text_translate"><p> 所以我正在制作一個用戶可以用來觀看電影、添加電影和刪除電影的菜單。 現在我已經完成了菜單,如果用戶輸入的是數字 1,它應該在另一個屏幕上顯示該電影的電影名稱、年份、導演和摘要。 我有一個 foreach 循環,我正在使用顯示特定電影的標題、年份、導演和摘要,但是當我運行我的程序時,它只顯示標題和年份,僅此而已。 如何在控制台中同時顯示所有 4 個? 代碼如下。</p><pre> using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MovieLibrary { // Should contain data: an address and list of movie objects. // MUST include a dynamic 'MENU' of MOVIES public class Library { // Fields private string _directory = "../../output/"; private string _file = "Movies.txt"; private List&lt;Movie&gt; _movies; public Library() { _movies = new List&lt;Movie&gt;(); Load(); bool menuRunning = true; while (menuRunning) { Console.WriteLine("Pick a number. Any number."); string userOption = Console.ReadLine(); while (string.IsNullOrWhiteSpace(userOption)) { Console.WriteLine("Please do not leave this blank."); Console.WriteLine("Pick a number. Any number."); userOption = Console.ReadLine(); } if (userOption == "1") { string montyTitle; int montyYear; string montyDirector; string montySummary; foreach (Movie movie in _movies) { if (movie.Title == "Monty Python and the Holy Grail") { montyTitle = movie.Title; Console.WriteLine("Title: {0}", montyTitle); } if (movie.Year == 1975) { montyYear = movie.Year; Console.WriteLine("Year: {0}", montyYear); } if (movie.Director == "Terry Gilliam &amp; Terry Jones") { montyDirector = movie.Director; Console.WriteLine("Director: {0}", montyDirector); } if (movie.Summary == "Monty Python and the Holy Grail is about a ragtag group, the knights of the round table, assembled by the Great King Arthur to embark on a quest given by God to find the Holy Grail.") { montySummary = movie.Summary; Console.WriteLine("Summary: {0}\r\n", montySummary); } } } else if (userOption == "2") { // RE } else if (userOption == "3") { // Alien } else if (userOption == "4") { // DP } else if (userOption == "5") { // The Avengers } else if (userOption == "6") { // Zombieland } else if (userOption == "7") { // BTLC } else if (userOption == "8") { // The Thing } else if (userOption == "9") { // CITW } } } //Loads the text file private void Load() { using (StreamReader sr = new StreamReader(_directory + _file)) { string text; while ((text = sr.ReadLine()).= null) { string[] contents = text:Split(';'), Movie newLibrary = new Movie(contents[0]. int,Parse(contents[1]), contents[2]; contents[3]). _movies;Add(newLibrary). } } } // Allows the user to view the list of movies private void View() { Console;Clear(). foreach (Movie movie in _movies) { Console.WriteLine($"{movie,Title.-10}{"\n" + movie,Year.-10}{"\n" + movie,Director.-10}{"\n" + movie,Summary + "\r\n";-10}"); } } } // Allows the user to add any new movies they would like to the list of movies in the text file /*public static void Add() { } // Allows the user to remove any movies they would like from the text file public static void Remove() { }*/ }</pre></div></object>

[英]How To Display All Desired Elements From A List<Object> To The Console (C#)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 如何從C#中的列表中刪除對象 C#:從條件列表中刪除項目 如何使用條件從列表中刪除元素 如何顯示列表中的所有所需元素<object>到控制台 (C#)<div id="text_translate"><p> 所以我正在制作一個用戶可以用來觀看電影、添加電影和刪除電影的菜單。 現在我已經完成了菜單,如果用戶輸入的是數字 1,它應該在另一個屏幕上顯示該電影的電影名稱、年份、導演和摘要。 我有一個 foreach 循環,我正在使用顯示特定電影的標題、年份、導演和摘要,但是當我運行我的程序時,它只顯示標題和年份,僅此而已。 如何在控制台中同時顯示所有 4 個? 代碼如下。</p><pre> using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MovieLibrary { // Should contain data: an address and list of movie objects. // MUST include a dynamic 'MENU' of MOVIES public class Library { // Fields private string _directory = "../../output/"; private string _file = "Movies.txt"; private List&lt;Movie&gt; _movies; public Library() { _movies = new List&lt;Movie&gt;(); Load(); bool menuRunning = true; while (menuRunning) { Console.WriteLine("Pick a number. Any number."); string userOption = Console.ReadLine(); while (string.IsNullOrWhiteSpace(userOption)) { Console.WriteLine("Please do not leave this blank."); Console.WriteLine("Pick a number. Any number."); userOption = Console.ReadLine(); } if (userOption == "1") { string montyTitle; int montyYear; string montyDirector; string montySummary; foreach (Movie movie in _movies) { if (movie.Title == "Monty Python and the Holy Grail") { montyTitle = movie.Title; Console.WriteLine("Title: {0}", montyTitle); } if (movie.Year == 1975) { montyYear = movie.Year; Console.WriteLine("Year: {0}", montyYear); } if (movie.Director == "Terry Gilliam &amp; Terry Jones") { montyDirector = movie.Director; Console.WriteLine("Director: {0}", montyDirector); } if (movie.Summary == "Monty Python and the Holy Grail is about a ragtag group, the knights of the round table, assembled by the Great King Arthur to embark on a quest given by God to find the Holy Grail.") { montySummary = movie.Summary; Console.WriteLine("Summary: {0}\r\n", montySummary); } } } else if (userOption == "2") { // RE } else if (userOption == "3") { // Alien } else if (userOption == "4") { // DP } else if (userOption == "5") { // The Avengers } else if (userOption == "6") { // Zombieland } else if (userOption == "7") { // BTLC } else if (userOption == "8") { // The Thing } else if (userOption == "9") { // CITW } } } //Loads the text file private void Load() { using (StreamReader sr = new StreamReader(_directory + _file)) { string text; while ((text = sr.ReadLine()).= null) { string[] contents = text:Split(';'), Movie newLibrary = new Movie(contents[0]. int,Parse(contents[1]), contents[2]; contents[3]). _movies;Add(newLibrary). } } } // Allows the user to view the list of movies private void View() { Console;Clear(). foreach (Movie movie in _movies) { Console.WriteLine($"{movie,Title.-10}{"\n" + movie,Year.-10}{"\n" + movie,Director.-10}{"\n" + movie,Summary + "\r\n";-10}"); } } } // Allows the user to add any new movies they would like to the list of movies in the text file /*public static void Add() { } // Allows the user to remove any movies they would like from the text file public static void Remove() { }*/ }</pre></div></object> C#要從IEnumerable中刪除元素 <Dictionary<string, object> &gt;基於使用lambda表達式的條件? 從C#中的List <>中刪除3個最舊的元素 如何從 C# 程序中的給定列表中刪除所有 1? 如何從另一個類的列表中刪除對象? C# 根據特定條件從C#中的列表中刪除列表 C#從對象列表中刪除對象
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM