I can't sort a column descending ASP MVC - c#

I need to sort the PROMEDIOCAL field in descending order but when implementing the sort it doesn't work. It lists me correctly by ID and I can also search by DISTRICT but I cannot sort the PROMEDIOCAL field in descending order when clicking on the header in the table
Controller:
public ActionResult ListarProfxServicio(int id, string CadenaBusqueda, string Orden)
{
List<TB_Profesionales> lista = new List<TB_Profesionales>();
ViewBag.cal = String.IsNullOrEmpty(Orden) ? "cod_asc" : "";
var data = from c in db.TB_Profesionales where c.IDSERVICIO == id select new {c.IDUSUARIO, c.NOMBRE, c.APELLIDO, c.SEXO, c.DISTRITO, c.DESCRIPCIÓN, c.PROMEDIOCAL};
var data2 = from c in db.TB_Profesionales select c;
foreach (var pro in data)
{
TB_Profesionales p = new TB_Profesionales();
p.IDUSUARIO = pro.IDUSUARIO;
p.NOMBRE = pro.NOMBRE;
p.APELLIDO = pro.APELLIDO;
p.SEXO = pro.SEXO;
p.DISTRITO = pro.DISTRITO;
p.DESCRIPCIÓN = pro.DESCRIPCIÓN;
p.PROMEDIOCAL = pro.PROMEDIOCAL;
lista.Add(p);
}
switch (Orden)
{
case "cod_asc":
data = data.OrderByDescending(s => s.PROMEDIOCAL);
break;
}
if (!String.IsNullOrEmpty(CadenaBusqueda))
{
data2 = data2.Where(s => s.DISTRITO.ToUpper().Contains(CadenaBusqueda.ToUpper()));
return View(data2.ToList());
}
return View(lista.ToList());
}
View:
<th>
#Html.ActionLink("Cod", "ListarProfxServicio", new {Orden = ViewBag.cal })
</th>

Problem
You are performing sorting in data but you are returning lista to the View. So your lista is never been sorted.
public ActionResult ListarProfxServicio(int id, string CadenaBusqueda, string Orden)
{
List<TB_Profesionales> lista = new List<TB_Profesionales>();
var data = from c in db.TB_Profesionales where c.IDSERVICIO == id select new {c.IDUSUARIO, c.NOMBRE, c.APELLIDO, c.SEXO, c.DISTRITO, c.DESCRIPCIÓN, c.PROMEDIOCAL};
...
foreach (var pro in data)
{
...
lista.Add(p);
}
switch (Orden)
{
case "cod_asc":
data = data.OrderByDescending(s => s.PROMEDIOCAL);
break;
}
...
return View(lista.ToList());
}
Solution
Change the below part to sort for lista.
switch (Orden)
{
case "cod_asc":
lista = lista.OrderByDescending(s => s.PROMEDIOCAL);
break;
}
Recommendation
The data and foreach part can be refactored together as:
List<TB_Profesionales> lista = from c in db.TB_Profesionales
where c.IDSERVICIO == id
select new TB_Profesionales
{
IDUSUARIO = c.IDUSUARIO,
NOMBRE = c.NOMBRE,
APELLIDO = c.APELLIDO,
SEXO = c.SEXO,
DISTRITO = c.DISTRITO,
DESCRIPCIÓN = c.DESCRIPCIÓN,
PROMEDIOCAL = c.PROMEDIOCAL
};

Related

Index out of bound of the array

i have this two methods to look for an object in a list of products, but when i try to ask to select one object to see i get the index out of bounds array(sorry that some of the code is in spanish)
Public Producto BuscarProducto(int id,List<Producto> prod)
{
var productos = ObtenerProducto();
var p = (from producto in productos
where producto.Id == id
select producto).First();
return p;
}
public List<Producto> ObtenerProducto()
{
var datos = ObtenerLineas();
List<Producto> productos = new List<Producto>();
foreach (var item in datos)
{
string[] info = item.Split(',');
Producto producto = new Producto
{
Id = int.Parse(info[0]),
Nombre = info[1],
Precio = double.Parse(info[2]),
Categoria = info[3],
Detalle = info[4]
};
productos.Add(producto);
}
return productos;
}
Make sure that there are four "," in the string that you are trying to split.
Also it would be better to check if there are atleast 5 elements in the array. You could try replacing your Add code with this checking.
if (info != null && info.Length >= 5)
{
Producto producto = new Producto
{
Id = int.Parse(info[0]),
Nombre = info[1],
Precio = double.Parse(info[2]),
Categoria = info[3],
Detalle = info[4]
};
productos.Add(producto);
}

how to get all the items of list c#

In a list i have 4 rows and I am try to get all the rows of the list but it is giving only one row, how to get all the rows of the list.
I have tried below code
public async Task<ResponseUserModel> get()
{
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
using (nae2sasqld0003Entities context = new nae2sasqld0003Entities())
{
var listt = context.Producers.Select(all => all).ToList();
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
}
}
please let me know where i to fix the issue
Use list to return all:
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
then
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
Note: change return type of the method to IList<ResponseUserModel>
or in this way
using (var context = new nae2sasqld0003Entities())
{
return context.Producers.Select(item =>
new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
}).ToList();
}

How to apply multiple optional filters in a LINQ query

I have a page where user can select any number of search filters to apply search
When user clicks on search, these parameters are passed to my GetIndicatorData method to perform the query. However, it doesn't seem to work for me.
Here is my code
public static List<tblindicators_data_custom> GetIndicatorsData(string status, int service_id, int operator_id, string year, string frequency)
{
var date = Convert.ToDateTime(year + "-01-01");
int[] numbers = status.Split(',').Select(n => int.Parse(n)).ToArray();
var ict = new ICT_indicatorsEntities();
var result = from ind in ict.tblindicators_data
join ser in ict.tblservices on ind.service_id equals ser.Id
join oper in ict.tbloperators on ind.operator_id equals oper.Id
where numbers.Contains(ind.status) && (ind.date_added.Year == date.Year)
select new
{
ind.Id,
ind.service_id,
ind.survey_id,
ind.operator_id,
ind.type,
ind.date_added,
ind.quater_start,
ind.quater_end,
ind.status,
ind.month,
service = ser.name,
operator_name = oper.name
};
List<tblindicators_data_custom> data = new List<tblindicators_data_custom>();
foreach (var item in result)
{
tblindicators_data_custom row = new tblindicators_data_custom();
row.Id = item.Id;
row.survey_id = item.survey_id;
row.service_id = item.service_id;
row.service_name = item.service;
row.operator_id = item.operator_id;
row.operator_name = item.operator_name;
row.date_added = item.date_added;
row.quater_start = item.quater_start;
row.type = item.type;
row.quater_end = item.quater_end;
row.month = item.month == null? DateTime.Now:item.month;
row.status = item.status;
data.Add(row);
}
return data;
}

Listing in WCF Entity

I have a problem with LINQ query (see comment) there is a First method and it only shows me the first element.
When I write in the console "Sales Representative" it shows me only the first element of it as in
I would like to get all of data about Sales Representative. How can I do it?
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
//Employee matchingProduct = database.Employees.First(p => p.Title == imie);
var query = from pros in database.Employees
where pros.Title == imie
select pros;
// Here
Employee pp = query.First();
pracownikDane = new PracownikDane();
pracownikDane.Tytul = pp.Title;
pracownikDane.Imie = pp.FirstName;
pracownikDane.Nazwisko = pp.LastName;
pracownikDane.Kraj = pp.Country;
pracownikDane.Miasto = pp.City;
pracownikDane.Adres = pp.Address;
pracownikDane.Telefon = pp.HomePhone;
pracownikDane.WWW = pp.PhotoPath;
}
return pracownikDane;
}
Right now you are just getting the .First() result from the Query collection:
Employee pp = query.First();
If you want to list all employees you need to iterate through the entire collection.
Now, if you want to return all the employee's you should then store each new "pracownikDane" you create in some sort of IEnumerable
public IEnumerable<PracownikDane> GetPracownik(string imie) {
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
var EmployeeList = new IEnumerable<PracownikDane>();
foreach(var pp in query)
{
EmployeeList.Add(new PracownikDane()
{
Tytul = pp.Title,
Imie = pp.FirstName,
Nazwisko = pp.LastName,
Kraj = pp.Country,
Miasto = pp.City,
Adres = pp.Address,
Telefon = pp.HomePhone,
WWW = pp.PhotoPath
});
}
return EmployeeList;
}
Then, with this returned List you can then do what ever you wanted with them.

IQueryable, converting Anonymous Type to Strong Type

Is there a more elegant/concise way of this; I'd like to get rid of foreach loop with the WorkListItem initialization code.
var queryable = registrations.Select(
r => new
{
r.Id, r.AccountNumber, r.DateAdded, r.DateUpdated, r.Patient, r.Patient.InsuranceInfos
});
var list = queryable.ToList();
var workListItems = new List<WorkListItem>();
foreach (var anonymous in list)
{
var w = new WorkListItem
{
Id = anonymous.Id,
ClientAccountId = anonymous.AccountNumber,
DateAdded = anonymous.DateAdded,
DateUpdated = anonymous.DateUpdated,
Patient = anonymous.Patient,
InsuraceInfos = anonymous.Patient.InsuranceInfos
};
workListItems.Add(w);
}
return workListItems;
Yes you can completely cut out the "middle-man" as it were and select straight into a new WorkListItem as below:
var list = registrations.Select(r => new WorkListItem
{
Id = r.Id,
ClientAccountId = r.AccountNumber,
DateAdded = r.DateAdded,
DateUpdated = r.DateUpdated,
Patient = r.Patient,
InsuraceInfos = r.Patient.InsuranceInfos
}).ToList();

Categories