Home > Software design >  Generic Linq List method remove last where count>1
Generic Linq List method remove last where count>1

Time:08-05

Trying to create a generic method why is it trying to convert List to List<List> ?

Error cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.List<System.Collections.Generic.List>'

List<string> mylist = new()
 {
    "item1", "item2"
 };

 RemoveRowWhereCountGreaterThan1<List<string>>(mylist);


 public  static void RemoveRowWhereCountGreaterThan1<T>(List<T> someList) where T : List<T>
 {
        someList.Where((c) => c.Count > 1).ToList().Remove(someList.Last());
 }

See DotNet Fiddle

CodePudding user response:

A few things wrong with your code:

  1. Your generic method specifies what the List should contain but when calling the method you specify the list itself rather than just what the list should contain

  2. Since, in your generic method, you provide a list parameter, you do not need the constrain that says the specified type can only be a list

  3. The actual generic method would not do what you wanted it to - the logic was slightly wrong and it would have created a new list and removed the value from that new list, leaving the original list unchanged

The following code should do what you wanted.

using System;
using System.Linq;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        List<string> mylist = new()
        {
            "item1", "item2"
        };

        RemoveRowWhereCountGreaterThan1<string>(mylist);
    }
    
    public static void RemoveRowWhereCountGreaterThan1<T>(List<T> someList) 
    { 
        if(someList.Count > 1)
        {
            someList.Remove(someList.Last());
        }
    }
        
}

CodePudding user response:

Your T type should be a List<T> so a List<List<T>>. But you pass a single list.

However, why you dont implement it as a params[]:

public static void RemoveRowWhereCountGreaterThan1<T>(params List<T>[] someLists)
{
    foreach(List<T> list in someLists)
    {
        if (list.Count > 0) list.RemoveAt(list.Count - 1);
    }
}

then you could use it with a single list or multiple:

RemoveRowWhereCountGreaterThan1(mylist);
RemoveRowWhereCountGreaterThan1(mylist, mylist2, mylist3);
RemoveRowWhereCountGreaterThan1(manyListsArray);
  • Related