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;
}
}
Key of Dictionary is a Student Object:
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; }
}
}
2
Answers
First off, where is the
Person
variable declared in your code?Secondly, why not just use:
No need to reinvent the wheel.
Furthermore, why not expand the
Person
class to hold the age and return aList<Person>
instead of aDictionary<string, int>
?Like this:
Then you can use it like this:
it’s much easier to understand and is less error-prone.
The main issue is in this snippet:
.Append()
is a LINQ extension method which does not modify the original collection, it simply returns a newIEnumerable
with the added element at the end. That means thatk
andv
stay empty, and the last for-cycle inhelpermethod
never runs. Sincek
andv
areList
, use.Add()
instead. Or even better, use ToDictionary.Other than that, I see a few more issues in your code:
should be
Dictionary<Person, int>
, it shouldn’t even compile as it is, since it does not match the return type ofhelpermethod
.should be
result.Add(p, v[i]);
,Person
is a type.