Home > Software design >  how to use linq instead of foreach to get an List<object>
how to use linq instead of foreach to get an List<object>

Time:04-05

        public List<object> Query()
        {
            List<string> availableBillingIncrements = _controller.GetAvailableDropdowns().AvailableBillingIncrement;
            List<object> results = new List<object>();

            var x = availableBillingIncrements
                .Select(i => new List<object> { "Increment", i })
                .ToList()
                .Select(i => new List<object> { i })
                .ToList();

            foreach (string increment in availableBillingIncrements)
            {
                List<object> result = new List<object>();
                result.Add(new List<object> { "Increment", increment });
                results.Add(result);
            }

            return results;
        }

in the code above x and results are the same objects except for the fact that x is of type List<List<object>> and results is List<object>. How can I get rid of foreach loop and use x as a results?

CodePudding user response:

You would need to cast the List<object> to object:

var results = availableBillingIncrements
    .Select(i => new List<object> { "Increment", i })
    .ToList()
    .Select(i => (object) new List<object> { i })
    .ToList();

Though this can be simplified to a single Select, and the intermediate ToList calls are not required:

var results = availableBillingIncrements
    .Select(i => (object) new List<object> {
        new List<object> { "Increment", i } })
    .ToList();
  • Related