Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# pass anonymous parameter?

Tags:

c#

Sorry for title, I cant find the correct one. I have more than one method that returns the same result.

returning type

public class JsonTreeView
{
    public int id { get; set; }
    public string text { get; set; }
    public string state { get; set; }
    public string @checked { get; set; }
    public string attributes { get; set; }
    public List<JsonTreeView> children { get; set; }
}

first method

List<JsonTreeView> FromReportTree(List<ReportTree> list)
{
}

second method

List<JsonTreeView> FromLocationTree(List<LocationTree> list)
{
}

and anothers... properties of Tree models are different. for example :

LocationTree (id, name, parent, text)
ReportTree (sno, name, parent, desc)

Is it possible to write one method for all these tree models? Any suggestion or starting point?

Thanks...

like image 997
AliRıza Adıyahşi Avatar asked May 05 '26 20:05

AliRıza Adıyahşi


2 Answers

I suggest that you make a private method that does the grunt work, and keep the overloaded methods for the different types. Call the private method from the other methods, with a function that creates a JsonTreeView object from the specific objects of that method:

private List<JsonTreeView> FromReportTree<T>(List<T> list, Func<T, JsonTreeView> convert) {
  // loop through the list and call convert to create items
  List<JsonTreeView> result = new List<JsonTreeView>();
  foreach (T item in list) {
    result.Add(convert(item));
  }
  return result;
}

List<JsonTreeView> FromReportTree(List<ReportTree> list) {
  return FromReportTree(list, t => new JsonTreeView(t.id, t.text, ... ));
}

List<JsonTreeView> FromReportTree(List<LocationTree> list) {
  return FromReportTree(list, t => new JsonTreeView(t.sno, t.desc, ... ));
}
like image 188
Guffa Avatar answered May 11 '26 16:05

Guffa


It depends on what happens in those methods. You say that the various Tree models have different properties; does the logic in the method need any of the non-common properties? If the logic in each of those methods is the same, you can do this:

List<JsonTreeView> FromReportTree<T>(List<T> list) where T : BaseTree
{
    //some logic
}

assuming you have a BaseTree model of some kind, otherwise T : class or just leave that off (not recommended).

If the logic differs, you can still do it like that by doing a check if (list is LocationTree) and using that to do the logic specific to LocationTree, but that can get messy.

like image 20
anaximander Avatar answered May 11 '26 15:05

anaximander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!