Home > front end >  C# Filter Tuple and Remove cast
C# Filter Tuple and Remove cast

Time:11-05

I have a method that will bring in a list of strings and an id, I have to return a tuple that will contain a list of strings and id, the tuple needs to be filtered and only return one string and one id and they cannot be the same what I am stuck on is how to get rid of the cast on return and i want to make sure each string that i am returning has the right associated id with it.

 public static List<(string,int)> ModifiedData(List<string?> changedData, int? id)
 {
     //declare a tuple to keep track of all changes and id
     var result = new List<(string change, int? cId)>();
     if (changedData != null)
     {
         foreach (var change in changedData)
         {
             //add the change and id to a list of tuples
             result.Add((change, id));
         }
     }
        
     //delete all of the same instances in the array and return and array
     var filteredChanges = result.Select(x => (x.change, x.cId)).Distinct();

     //return the tuple** how can i also get rid of this cast
     return (List<(string, int)>)filteredChanges;
 }

CodePudding user response:

Currently your cast would throw an exception at runtime, since it's not a list.

You could simplify your code significanly:

public static List<(string, int)> ModifiedData(List<string?> changedData, int? id)
{
    return changedData?
        .Select(s => (s, id.GetValueOrDefault()))
        .Distinct()
        .ToList() ?? new List<(string, int)>(0);
}

However, maybe you want to add null checks for the string and/or the id. You could add a Where:

return changedData?
    .Where(s => s != null)
    .Select(s => (s, id.GetValueOrDefault()))
    .Distinct()
    .ToList() ?? new List<(string, int)>(0);
  • Related