locked
combine two db calls in single call RRS feed

  • Question

  • User527076549 posted

    How to combine below 2 db calls to one .Is it possible ?

    IEnumerable<int> NewIds= Table1.NewValue.Split(',').Where(x => int.TryParse(x, out int num)).Select(int.Parse).ToList();
    if (NewIds!= null && NewIds.Count() > 0)
    {
    NewValue = string.Join(",", _context.table1.Where(x => NewIds.Contains(x.Id)).Select(x => TempTextHelper.L(x.Name)));
    }
    IEnumerable<int> oldIds = Table1.OldValue.Split(',').Where(x => int.TryParse(x, out int num)).Select(int.Parse).ToList();
    if (oldIds != null && oldIds.Count() > 0)
    {
    OldValue = string.Join(",", _context.table1.Where(x => oldIds.Contains(x.Id)).Select(x => TempTextHelper.L(x.Name)));
    }

    Thanks And Regards,

    Monday, June 1, 2020 11:22 AM

Answers

  • User-719153870 posted

    Hi amithashenoy,

    The common approach to combine these two similar lines of code into one is to create a common method.

    Please check below demo, this is not based on db but it should make the solution clear.

    class Program
        {
            static void Main(string[] args)
            {
                List<Student> list = new List<Student>() {};
                list.Add(new Student { Id = 123 });
                list.Add(new Student { Id = 456 });
                Table1 table = new Table1 {OldValue="123,456",NewValue="123,455" };
                var result = Getvalue(table, "NewValue", list);
            }
            static string Getvalue(Table1 table,string property,List<Student> list)
            {
                string result = string.Empty;
                IEnumerable<int> NewIds = table.GetType().GetProperty(property).GetValue(table, null).ToString().Split(',').Where(x => int.TryParse(x, out int num)).Select(int.Parse).ToList();
                if (NewIds != null && NewIds.Count() > 0)
                {
                    result = string.Join(",", list.Select(x => NewIds.Contains(x.Id)));
                }
                else
                {
                    return string.Empty;
                }
                return result;
    
     
    
            }
        }
        public class Table1
        {
            public string OldValue { get; set; }
            public string NewValue { get; set; }
        }
    
     
    
        public class Student
        { 
        
         public int Id { get; set; }
        
        }

    Best Regard,

    Yang Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 2, 2020 3:26 AM