Home > Software engineering >  Genereric.List to a Dictionary/List
Genereric.List to a Dictionary/List

Time:10-28

I have a method that I receive a FormCollection. And I need to pass to my application layer a list of it.

What I'm doing and works:

var formIndexes = form.AllKeys.Select((e, i) => new { Name = e, Index = i }).Where(o => o.Name.Contains("StatusId")).ToList();
var formValues = formIndexes.Select(e => new { Value = form[e.Index], Name = e.Name }).ToList();

but formValues is a Generic.List and I need to convert to a List or a Dictionary.

Error: cannot convert from 'System.Collections.Generic.List<<anonymous type: string Value, string Name>>' to 'System.Collections.Generic.Dictionary<string, string>'

[SOLVED]

As @DanielA.White said, I solved doing:

formIndexes.Select(e => new { Value = form[e.Index], Name = e.Name }).ToDictionary(a => a.Name, b => b.Value);

CodePudding user response:

According to the error text, the final result should be a dictionary, not a list. test this

var formValues = formIndexes.ToDictionary(x => x.Index, x => x.Name);

CodePudding user response:

FormcCollection, if you check the source, has already accessors set. So it can be accessed as a dictionary without need to convert it:

        [HttpPost] 
        public ActionResult Submit(FormCollection fc)
        {
            ViewBag.Id = fc["Id"];
            ViewBag.Name = fc["Name"];
            bool chk = Convert.ToBoolean(fc["Addon"].Split(',')[0]);
            ViewBag.Addon = chk;

            return View("Index");
        }

Check here for further explanation

  • Related