I am passing a list of objects from the Controller to a function in a Helper Class which is to return a dictionary back. However, the return value I am getting is always nothing. My list of objects works fine and the values are present so the error is in the helper class.
This is my Controller:
[HttpPost]
public ActionResult Form(List<Student> s)
{
var c = new HelperClass();
var result = c.helpermethod(s);
ViewBag.Result = s.Count; // RETURNS CORRECT LENGTH
ViewBag.Value = result.Count; // ALWAYS RETURN ZERO
return View("Index");
}
Method in my Helper Class :
public Dictionary<Person,int> helpermethod(List<Student> s)
{
var result = new Dictionary<string, int>();
List<string> k = new List<string>();
List<int> v = new List<int>();
for (int i = 0; i < s.Count; i++)
{
var d = s[i];
if (k.Contains(d.Name)){
int index = k.FindIndex(a => a == d.Name);
v[index]+= d.Age;
}
else {
k.Append(d.Name);
v.Append(d.Age);
}
}
// Create Dictionary
for (int i = 0; i < k.Count; i++)
{
var p= new Person(k[i]) ;
result.Add(Person, v[i]);
}
return result;
}
Dictionary is Person Object:
public class Person
{
public string p { get; set; }
// Intializing class
public Person(string x)
{
p = x;
}
}
This is my model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCModel.Models
{
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
}
The main issue is in this snippet:
else {
k.Append(d.Name);
v.Append(d.Age);
}
.Append()
is a LINQ extension method which does not modify the original collection, it simply returns a new IEnumerable
with the added element at the end. That means that k
and v
stay empty, and the last for-cycle in helpermethod
never runs. Since k
and v
are List
, use .Add()
instead. Or even better, use ToDictionary.
Other than that, I see a few more issues in your code:
var result = new Dictionary<string, int>();
should be Dictionary<Person, int>
, it shouldn't even compile as it is, since it does not match the return type of helpermethod
.
result.Add(Person, v[i]);
should be result.Add(p, v[i]);
, Person
is a type.