Home > Net >  Remove Items from list with priority
Remove Items from list with priority

Time:12-29

Lets suppose i have a list and i want to remove accoding to the condition that if priority item is there then remove all smaller priority items . for eg

arr[] =["world champion","Best performer","Best gold", "Best silver", "Best bronze", "regional"]

Conditions.

  1. if gold is present i want every medal except silver and bronze.
  2. if gold is not presnt but max silver is present then show only silver not bronze
  3. if both silver and gold are not present then show bronze.

the array would always be sorted so always gold>siilver>bronze would be the order.

My implementation is working but i dont think its the optimised way of doing it.

    if(arr.Contains("Best gold")){
                sortedArr.RemoveAll(x => ((string)x) == "Best silver" 
                 || ((string)x) == "Best Bronze" );
            }
    if (sortedArr.Contains("Best silver")) {
                sortedArr.RemoveAll(x =>((string)x) == "Best bronze");
            }
         

thank you in advance

CodePudding user response:

Your question is not clear. but you can use Array.IndexOf Method to check item is present:

List<string> array =(new string[] {"world champion", "Best performer", "Best gold", "Best silver", "Best bronze", "regional"}).ToList();

if (array.IndexOf("Best gold") > 0) 
    array.RemoveAll(m=>m.Contains("Best silver") || m.Contains("Best bronze"));

else if (array.IndexOf("Best silver") > 0)
    array.RemoveAll(m => m.Contains("Best bronze"));

CodePudding user response:

List<string> array =(new string[] {"world champion", "Best performer", "Best gold", "Best silver", "Best bronze", "regional"});

    array.Contains("Best gold")  ? array.RemoveAll(x => ((string)x) == "Best silver" || ((string)x) == "Best Bronze" ) 
                                 : (array.Contains("Best silver") ?
                                  array.RemoveAll(x =>((string)x) == "Best bronze")
                                 : return array)
                         
  • Related