I Had to duplicate this method (made by another person) but I wanna know if there is a way to unify it,
this one receives an IList<ViewModelA>
, I need to pass to it an IList<ViewModelB>
with different properties, but the ones used in the method are in both are the same like fatherId
or Items
I wanna know if there is a way to unify those methods with inheritance or interface or something else.
private IList<ViewModelA> TrasnformToTree(IEnumerable<ViewModelA> source)
{
var modelGroups = source.GroupBy(i => i.fatherId);
var roots = modelGroups.FirstOrDefault(g => g.Key.HasValue == false).ToList();
if (roots.Count > 0)
{
var dict = modelGroups.Where(g => g.Key.HasValue)
.ToDictionary(g => g.Key.Value, g => g.ToList());
for (int i = 0; i < roots.Count; i++)
{
if (dict.ContainsKey(roots[i].Id))
{
roots[i].Items = dict[roots[i].Id];
for (int j = 0; j < roots[i].Items.Count; j++)
AddChildren(roots[j].Items[j], dict);
}
else
{
roots[i].Items = new List<ViewModelA>();
}
}
}
return roots;
}
this should work for the code i'm seeing:
private interface ISomeInterface<T>
{
int Id { get; set; }
int? fatherId { get; set; }
List<T> Items { get; set; }
}
private IList<T> TrasnformToTree<T>(IEnumerable<T> source) where T : ISomeInterface<T>
{
var modelGroups = source.GroupBy(i => i.fatherId);
var roots = modelGroups.FirstOrDefault(g => g.Key.HasValue == false).ToList();
if (roots.Count > 0)
{
var dict = modelGroups.Where(g => g.Key.HasValue)
.ToDictionary(g => g.Key.Value, g => g.ToList());
for (int i = 0; i < roots.Count; i++)
{
if (dict.ContainsKey(roots[i].Id))
{
roots[i].Items = dict[roots[i].Id];
for (int j = 0; j < roots[i].Items.Count; j++)
AddChildren(roots[j].Items[j], dict);
}
else
{
roots[i].Items = new List<T>();
}
}
}
return roots;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.