Building an OrderBy Lambda expression based on child entity's property

后端 未结 5 1736
渐次进展
渐次进展 2020-12-10 04:34

I\'m trying to generate a LINQ OrderBy clause using lambda expressions with an input of the column name of an entity as a string (in the \"sortOn\" variable bel

5条回答
  •  粉色の甜心
    2020-12-10 04:52

    Hi you can also create an extension method like which can sort to any depth not only just child

            public static IEnumerable CustomOrderBy(this IEnumerable source, Func keySelector)
        {
            List list=new List();
            List returnList=new List();
            List indexList = new List();
    
            if (source == null)
                return null;
            if (source.Count() <= 0)
                return source;
            source.ToList().ForEach(sc=>list.Add(keySelector(sc).ToString())); //Extract the strings of property to be ordered
    
            list.Sort(); //sort the list of strings
    
            foreach (string l in list) // extract the list of indexes of source according to the order
            {
                int i=0;
                //list.ForEach(l =>
    
                    foreach (var s in source.ToList())
                    {
                        if (keySelector(s).ToString() == l)
                            break;
                        i++;
                    }
                    indexList.Add(i);
            }
            indexList.ForEach(i=>returnList.Add(source.ElementAt(i))); //rearrange the source according to the above extracted indexes
            return returnList;
        }
    }
    public class Name
    {
        public string FName { get; set; }
        public string LName { get; set; }
    }
    public class Category
    {
        public Name Name { get; set; }
    }
    public class SortChild
    {
        public void SortOn()
        {
            List category = new List{new Category(){Name=new Name(){FName="sahil",LName="chauhan"}},
                new Category(){Name=new Name(){FName="pankaj",LName="chauhan"}},
                new Category(){Name=new Name(){FName="harish",LName="thakur"}},
                new Category(){Name=new Name(){FName="deepak",LName="bakseth"}},
                new Category(){Name=new Name(){FName="manish",LName="dhamaka"}},
                new Category(){Name=new Name(){FName="arev",LName="raghaka"}}
            };
            var a = category.CustomOrderBy(s => s.Name.FName);
    
        }
    
    }
    

    Its custom method and right now it works only for string property only however it can be reactified using generics to work for any primitive type. I hope this will help.

提交回复
热议问题