Home > front end >  Pass a generic list to a fuction and sort it (.Net Framework 4.8)
Pass a generic list to a fuction and sort it (.Net Framework 4.8)

Time:12-30

I have this function:

private void ReadFilesCommon<T>(string path, List<Class> Data, IParser Iparser, Func<KeyValuePair<string, object>, T> ClassCreator)
        {
            foreach (List<KeyValuePair<string, object>> entry in Iparser.ParseFiles(path)) // Files
            {
                foreach (KeyValuePair<string, object> entry2 in entry)
                {
                    Data.Add(ClassCreator(entry2));
                }
            }

            Data.Sort(delegate (Class t1, Class t2)
            {return (t1.name.CompareTo(t2.name));});

            
            return;
        }

Being Class the variable.

I want to make a function that can receive a list of some class (that has .name in it) and be able to sort it.

The problem is, if i make it generic, it loses the .name, so i can't sort it.

CodePudding user response:

You need either introduce an interface (or abstract class) which will expose the name property, implement it in the corresponding classes and restrict generic type to it via constraint:

public class IHaveName
{
   public string name {get; set;}
} 

private void ReadFilesCommon<T>(string path, 
    List<T> Data, 
    IParser Iparser, 
    Func<KeyValuePair<string, object>, T> ClassCreator) where T : IHaveName
{
    // ...
}

Or provide extra parameter which will represent function returning the sort field, depending on how generic you want it be it can be just string or another generic parameter:

private void ReadFilesCommon<T>(string path, 
    List<T> Data, 
    IParser Iparser, 
    Func<KeyValuePair<string, object>, T> ClassCreator, 
    Func<T, string> sortBy
)
{
    // ...
    Data.Sort(delegate (T t1, T t2)
            {return (sortBy(t1).CompareTo(sortBy(t2)));});
}

And usage looking something like ReadFilesCommon(..., t => t.name).

P.S. I recommend to follow standard naming conventions.

CodePudding user response:

I am not sure about your List<Class> type. I think you might be confused about generics, but that's just me. But I hope this helps:

I would classes implement IComparable:

void ReadFilesCommon<T>(...) where T : IComparable
{
    ...
    // you don't need delegate
    data.Sort();
}

..or pass in IComparer (or your delegate) as an additional argument:

void ReadFilesCommon<T>(... ICopmarer<T> comparer)
{
    ...
    data.Sort(comparer);
}

See List.Sort docs for more.

  •  Tags:  
  • c#
  • Related