Not Returning properly - c#

I was trying to get employee list which not already available in another list. but im getting only first element from array list.
ex : if i try EmployeeId = new int[2] {5, 2}; the list excluding only '5'. So please help me correct my below code.
public JsonResult GetEmployees(int[] EmployeeId)
{
var dbs = new dbContext();
if (EmployeeId != null)
{
foreach (var emp in EmployeeId)
{
var EmpList = dbs.Employees.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
}).Where(o => o.EmployeeId != emp);
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
}
return null
}

Try this :
var employeeList = dbs.Employees.
.Where(e => EmployeeId.All(x=> x != e.EmployeeId))
.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
});
return Json(EmpList, JsonRequestBehavior.AllowGet);
}

Have you tried stepping through your code?
Your foreach iterates over your EmployeeId array.
Since you have a return statement in your foreach it exits the function at that point and it only uses the first element of your array.
You need something like this:
public JsonResult GetEmployees(int[] EmployeeId)
{
var dbs = new dbContext();
if (EmployeeId != null)
{
var EmpList = dbs.Employees.Where(EmployeeId.Contains(e.EmployeeId))
.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
}).Where(o => o.EmployeeId != emp);
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
return null;
}

Related

Unable to Convert Linq to Lambda Notation

public ActionResult EditArticle(int id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var typeId = 0;
var catId = 0;
var subCatId = 0;
var viewModel = (from sa in ems.SupportArticles
join ssc in ems.SupportSubCategories on sa.SubCatID equals ssc.SubCatID
join sc in ems.SupportCategories on ssc.CatID equals sc.CatID
join st in ems.SupportTypes on sc.TypeID equals st.TypeID
where sa.ArcticleId == id
select new SupportArticleViewModel { supportArticle = sa, supportSubCat = ssc, supportCat = sc, supportType = st });
foreach (var vm in viewModel)
{
typeId = vm.supportType.TypeID;
catId = vm.supportCat.CatID;
subCatId = vm.supportSubCat.SubCatID;
}
I want to convert it into Lambda Notation.But, I am unable to do it.Please help.I am using SupportViewModel which contains property of SupportType,SupportCategory ,SupportSubCategoryand SupportArticle.
Following is functional way do query , you have to make use of join function and than you get data
var filteredArtciles = SupportArticles.Where(sa=> sa.ArcticleId == id);
var query =
SupportArticles.
Join(SupportSubCategories,sa => sa.SubCatID ,ssc => ssc.SubCatID,(sa, ssc) => new {sa,ssc}).
Join(SupportCategories,sassc => sassc.ssc.CatID ,sc=>sc.CatID ,(sassc, sc) => new {sassc,sc}).;
Join(SupportTypes,sasscsc => sasscsc.sc.TypeID ,st=>st.TypeID ,(sc, st) => new {sasscsc,st}).
Select(j=>
new SupportArticleViewModel
{
supportArticle = j.sasscsc.sassc.sa,
supportSubCat = j.sasscsc.sassc.ssc,
supportCat = j.sasscsc.sc,
supportType = j.st
}
));

Merge two Lists of same type with diff values and avoid duplicates

I have two lists of same type with different key value pairs,
List1 has "isPermanent = true" and List2 has false value and also
List1 has an extra key "nextVacationDate".
Im trying to do union of these as below but im afraid I will still get the duplicates because of different values. I need to merge both lists in to one list and order by List1 first (Permanent employees first)..is there a better way to do this using LINQ?
public newList1 List1(string abcd)
{
var result = serviceMethod1(abcd);
var newList1 = new List<emp>();
if (result == null) return null;
newList.AddRange(
result.Select(x => new Model
{
firstName = x.FName,
secondName = x.SName,
address = x.Address,
employeeId = x.EmpId,
isPermanent = true,
nextVacationDate =x.VacDt,
salary = x.Bsalary
}));
return newList1;
}
public newList2 List2(string defg)
{
var result = serviceMethod2(defg);
var newList2 = new List<emp>();
if (result == null) return null;
newList.AddRange(
result.Select(x => new Model
{
firstName = x.FName,
secondName = x.SName,
address = x.Address,
employeeId = x.EmpId,
isPermanent = false,
salary = x.Bsalary
}));
return newList2;
}
private List<emp> EmployyeList(List<emp> newList1, List<emp> newList2)
{
var sortedEmpList1 = newList1.OrderBy(i => i.Fname);
var sortedEmpList2 = newList2.OrderBy(i => i.Fname);
List<MeterModel> combinedList = newList1.Union(newList2) as List<emp>;
return combinedList;
}
You can filter the 2nd list to avoid duplicates:
newList1.Union(newList2.Where(emp2 => !newList1.Any(emp1 => emp1.employeeId == emp2.employeeId)))

Iterating through a list of view models and calculating values

I have an AddToCart action method which adds products to a cart via ajax, it basically works fine but sometimes (I cannot pinpoint it) e.g. I add a few products from one category, and then a few from another and the total doubles, so e.g. if I add 3 from one category, and then 1 from another it will be 4, and then again it will be 10! And then it will go on as normal.
Can you see what is wrong with this code?
public ActionResult AddToCart(string id)
{
List<CartVM> cartVMList = new List<CartVM>();
CartVM cartVM = new CartVM();
int productId = Int32.Parse(id);
int qty = 0;
decimal price2 = 0;
Db db = new Db();
var result = db.Products.FirstOrDefault(x => x.Id == productId);
decimal price = result.Price;
cartVM.ProductId = productId;
cartVM.Quantity = 1;
cartVM.Price = price;
if (Session["cart"] != null)
{
cartVMList = (List<CartVM>)Session["cart"];
var itemToEdit = cartVMList.FirstOrDefault(x => x.ProductId == productId);
if (itemToEdit == null)
{
cartVMList.Add(cartVM);
}
else
{
itemToEdit.Quantity++;
}
foreach (var item in cartVMList)
{
qty += item.Quantity;
price2 += item.Quantity * item.Price;
}
cartVM.Quantity = qty;
cartVM.Price = price2;
}
else
{
cartVMList.Add(cartVM);
Session["cart"] = cartVMList;
}
return PartialView(cartVM);
}
Basically the if (Session["cart"] != null) part is the meat of it and where the problem is I presume.
Your method contains a lot of unnecessary things and can be simplified a lot:
public ActionResult AddToCart(int productId)
{
// get a cart from session or create new
var cart = Session["cart"] as List<CartVM> ?? new List<CartVM>();
using(var db = new Db())
{
// get product in question
var product = db.Products
.FirstOrDefault(x => x.Id == productId)
// if this is unknown product, throw exception
if(product == null)
{
thrown new ArgumentException("Invalid product", nameof(productId));
}
// get existing line
var existingCartLine = cart
.FirstOrDefault(x => x.ProductId == productId);
// if there was no existing line, add a new one
if(existingCartLine == null)
{
cart.Add(new CartVM
{
ProductId = product.Id,
Quantity = 1,
Price = product.Price,
TotalPrice = product.Price
});
}
else
{
// otherwise modify existing line
existingCartLine.Quantity++;
existingCartLine.TotalPrice = cartLine.Price * cartLine.Quantity;
}
}
// save cart back in the session
Session["cart"] = cart;
// return view
return PartialView(cart);
}

How to sort C# Jobject

In my model I have public JObject GenericData { get; set; } for this property I need to create Jobject in my Controller that will pass data to this property. I have done this but now I need to sort data inside Jobject and I don't know how to do it. There is no sort function for Jobject out of box.
My code in controller looks like this.
var attributes = _context.AttributeRecords.Include(a => a.Attribute);
var queryRecords = attributes.Select(l => new
{
RecordId = l.RecordId,
ProjectId = l.ProjectId,
Attribute = l.Attribute.Description,
Value = l.Value,
InfoId = l.InfoId
}).ToList();
var recordsValues = queryRecords.Where(b => b.InfoId == i.InfoId).ToList();
var jObjectValues = new JObject();
foreach (var n in recordsValues)
{
if (n.Value.Contains(","))
{
var stringToSplit = n.Value;
var stringValues = stringToSplit.Split(',');
List<string> arr = new List<string>();
var allValues = "";
foreach (var d in stringValues)
{
var values = await _context.AttributeValues.FirstOrDefaultAsync(v => v.Key == n.Value);
arr.Add(values != null ? values.Description : d);
allValues = string.Join(",", arr);
}
jObjectValues.Add(n.Attribute, allValues);
}
else
{
var values = await _context.AttributeValues.FirstOrDefaultAsync(v => v.Key == n.Value);
jObjectValues.Add(n.Attribute, values != null ? values.Description : n.Value);
}
i.GenericData = jObjectValues;
}
You don't need to sort Jobject you can do it like this:
var queryRecords = attributes.Select(l => new
{
RecordId = l.RecordId,
ProjectId = l.ProjectId,
Attribute = l.Attribute.Description,
Value = l.Value,
InfoId = l.InfoId
}).OrderBy(o => o.Attribute).ToList();
I hope this will help you.

How to set query to get result as below?

I have the table structure as below,
I need the result like :
Redbook
|______Wedding
|______Christian
|______Muslim
|______Hindu
|______Birthday
|______Baptism
Which means, parentID having 0 should be the root and who's id(here 1) as parentID are its children (ie., wedding,birthday,Baptism) and so on...
I tried something like:
public List<specdetails> getProductDet(int ID)
{
List<specdetails> result;
using (APM context = new APM())
{
var res = (from s in context.M_CategoryDetails where s.CategoryID == ID select s).ToList();
result = res
.GroupBy(u=>u.ParentID)
.Select(grp => new specdetails
{
parentID = (int)grp.Key,
//ImageList = grp.ToList()
description = grp.FirstOrDefault().Description,
ID = grp.FirstOrDefault().ID,
catID = (int)grp.FirstOrDefault().CategoryID,
vPath = grp.FirstOrDefault().VirtualPath
}
).ToList();
}
return null; //result;
}
But it does not accomplish my needs.Please help.

Categories

Resources