I am trying to modify the existing implementation.I need to add three new properties inside in children.
I have those properties inside the temp list .I need to fetch from the temp list but could not able to proceed.
List<EmployeeModel> temp = Response.ResponseData.OrderBy(x =>
x.EmployeeNumber).ToList();
var results = temp.GroupBy(p => p.Empoyeegroup.Name, p => (p.Empoyeegroup.Name + "_" + p.Empoyeenumber.ToString()),
(key, g) => new FoodNode
{
Name = key,
Children = new List<FoodNode>(from pp in g
select new FoodNode { Name = pp}).ToList()
});
````
Solution 1:
Select all required properties in group by and use them later. please check example.
var results = temp.GroupBy(p => p.Empoyeegroup.Name, p => new {Name=p.Empoyeegroup.Name + "_" + p.Empoyeenumber.ToString(),Extra=p.Empoyeenumber},
(key, g) => new FoodNode
{
Name = key,
Children = new List<FoodNode>(from pp in g
select new FoodNode { Name = pp.Name,ExtraProp = pp.Extra}).ToList()
});
Solution 2:
Select full object in group by instead of limited properties and use them whatever property required. Please check example.
var results = temp.GroupBy(p => p.Empoyeegroup.Name, p => p,
(key, g) => new FoodNode
{
Name = key,
Children = new List<FoodNode>(from pp in g
select new FoodNode { Name = (pp.Empoyeegroup.Name + "_" + pp.Empoyeenumber.ToString()),ExtraProp = pp.Empoyeenumber }).ToList()
});
Related
I have a code like this:
using (var ws = new WebService())
using (var db = new EntityFrameworkModel())
{
var originalFolders = ws.GetFolders();
foo.folders = originalFolders.Select(c => new FolderType()
{
Id = c.Description,
Items = ws.ListDocs(c.Id)
.Select((d, i) =>
new DocType()
{
Id = StaticMethod(d, c),
Order = i,
SomeValue = db.docs.Single(doc => doc.Id == StaticMethod(d, c)).SomeValue
}
).ToArray()
}).ToArray();
}
But I get a "LINQ to Entities does not recognize the method 'StaticMethod' method, and this method cannot be translated into a store expression" exception. Does exist any way to pass a static value as a parameter? Something like this:
using (var ws = new WebService())
using (var db = new EntityFrameworkModel())
{
var originalFolders = ws.GetFolders();
foo.folders = originalFolders.Select(c => new FolderType()
{
Id = c.Description,
Items = ws.ListDocs(c.Id)
.Select((d, i, string myValue = StaticMethod(d, c)) =>
new DocType()
{
Id = myValue,
Order = i,
SomeValue = db.docs.Single(doc => doc.Id == myValue).SomeValue
}
).ToArray()
}).ToArray();
}
I can't modify DocType class constructor. Does exist any way?
Usually this is a matter of making sure you don't inline functions in linq-to-SQL expressions that can't be turned into valid SQL.
Try this:
using (var ws = new WebService())
using (var db = new EntityFrameworkModel())
{
var originalFolders = ws.GetFolders();
foo.folders = originalFolders.Select(c => new FolderType()
{
Id = c.Description,
Items = ws.ListDocs(c.Id)
.Select((d, i) =>
{
var id = StaticMethod(d, c);
return new DocType()
{
Id = id,
Order = i,
SomeValue = db.docs.Single(doc => doc.Id == id).SomeValue
};
}).ToArray()
}).ToArray();
}
I've table with following data.
I want to group the data by DocumentID and then want to marge the DocPropIdentifyName and meta value together using comma separator. The output will be like following:
I'm doing it by using a foreach like below:
var test = (from r in lstDocSearch
group r by r.DocumentID
into g
select new
{
DocumentID = g.Key,
MetaValues = g.ToList()
}).ToList();
List<DocSearch> list = new List<DocSearch>();
foreach (var item in test)
{
foreach (var item2 in item.MetaValues)
{
var check = list.Exists(x => x.DocumentID == item2.DocumentID);
if (check)
{
var find = list.FirstOrDefault(x => x.DocumentID == item2.DocumentID);
find.MetaValue = find.MetaValue + ", " + item2.MetaValue;
find.DocPropIdentifyName = find.DocPropIdentifyName + ", " + item2.DocPropIdentifyName;
}
else
{
DocSearch objDocSearch = new DocSearch();
objDocSearch.DocumentID = item2.DocumentID;
objDocSearch.DocPropIdentifyID = item2.DocPropIdentifyID;
objDocSearch.DocPropIdentifyName = item2.DocPropIdentifyName;
objDocSearch.MetaValue = item2.MetaValue;
list.Add(objDocSearch);
}
}
}
But I would like to do this with linq rather than looping through the collection. Is it possible?
Do you mean something like this ? :
var test = (from r in lstDocSearch
group r by r.DocumentID
into g
select new
{
DocumentID = g.Key,
MetaValues = String.Join(",", g.Select(o => o.MetaValue)),
DocPropIdentifyNames = String.Join(",", g.Select(o => o.DocPropIdentifyName)),
}).ToList();
I have a ControlMeasure table that holds information on each control measure and a ControlMeasurepeopleExposed Table that holds a record for each person exposed in the control measure this could be 1 record or many records.
I Have a controller that populates a List view
For each item in the list, Control Measure, I would like to create a string that shows all the People at risk
e.g.
PeopleString = "Employees, Public, Others";
Ive added a foreach in the controller to show what I'm trying to do however I'm aware that this wont work.
The controller is this:
public ActionResult ControlMeasureList(int raId)
{
//Populate the list
var hazards = new List<Hazard>(db.Hazards);
var controlMeasures = new List<ControlMeasure>(db.ControlMeasures).Where(x => x.RiskAssessmentId == raId);
var cmcombined = (
from g in hazards
join f in controlMeasures
on new { g.HazardId } equals new { f.HazardId }
select new CMCombined
{
Activity = f.Activity,
ControlMeasureId = f.ControlMeasureId,
ExistingMeasure = f.ExistingMeasure,
HazardName = g.Name,
LikelihoodId = f.LikelihoodId,
Rating = f.Rating,
RiskAssessmentId = f.RiskAssessmentId,
SeverityId = f.SeverityId,
}).OrderBy(x => x.Activity).ToList();
var cmPeopleExp = new List<ControlMeasurePeopleExposed>(db.ControlMeasurePeopleExposeds).Where(x => x.RiskAssessmentId == raId);
var peopleExp = from c in cmPeopleExp
join d in db.PeopleExposeds
on c.PeopleExposedId equals d.PeopleExposedId
orderby d.Name
select new RAPeopleExp
{
RAPeopleExpId = c.PeopleExposedId,
PeopleExpId = c.PeopleExposedId,
PeopleExpName = d.Name,
RiskAssessmentId = c.RiskAssessmentId,
ControlMeasureId = c.ControlMeasureId
};
var model = cmcombined.Select(t => new FullControlMeasureListViewModel
{
ControlMeasureId = t.ControlMeasureId,
HazardName = t.HazardName,
LikelihoodId = t.LikelihoodId,
Rating = t.Rating,
SeverityId = t.SeverityId,
Activity = t.Activity,
ExCM = t.ExistingMeasure,
//This section here is where I'm struggling
var PeopleString = new StringBuilder();
foreach (var p in peopleExp)
{
PeopleString.AppendLine(p.PeopleName);
{
PeopleExposed = PeopleString,
});
return PartialView("_ControlMeasureList", model);
}
I know I cant directly put this code in the controller but it does represent what I want to do.
You can't foreach within an object initializer (which is what you're trying to do when instantiating FullControlMeasureListViewModel). You can, however, use a combination of string.Join and peopleExp.Select:
var model = cmcombined.Select(t => new FullControlMeasureListViewModel
{
//other props
PeopleExposed = string.Join(",", peopleExp
.Where(p => p.ControlMeasureId == t.ControlMeasureId)
.Select(p => p.PeopleExpName));
//other props
});
So i have following two list using linq.
List<One> one= A.Common
.Join(B.Common,
a => a.ID,
b=> b.ID,
(a, b) => new One
{
ID = b.PID,
Name = b.PCName,
LastName = a.LName
}).ToList();
List<One> two = (from c in D.Options
select new One
{
MainName = c.mName
}).ToList();
List<One> sn = one.Concat(two).ToList();
I am concating both list. But when i debug i am getting MainName as null in sn list.
How do i get data from both list in single list??
This is how you do it:
var sn = one.Zip(two, (x, y) => new One{
ID = x.ID,
Name = x.Name,
LastName = x.LastName,
MainName = y.MainName
});
You want the MainName property assigned for all the list values in List ONE ?
As from above code concatenation will join two list and the MainName will be not set for list one elements.
one.Concat(two)
Above line will just concat the both lists to one list elements.
You can use the LINQ Concat and ToList methods:
var mergedList = YourFirstList.Concat(YourSecondList)
.Concat(YourThirdList)
.ToList();
Edit:
one.Concat(two).Select(g => g.Aggregate((p1,p2) => new One
{
ID = p1.ID,
Name = p1.PCName,
LastName = p1.LName,
MainName = p2.mName
}));
more efficient ways to do this - the above will basically loop through all the entries, creating a dynamically sized buffer.
var mergedList = new List<One>(YourFirstList.Count +
YourSecondList.Count +
YourThirdList.Count);
mergedList.AddRange(YourFirstList);
mergedList.AddRange(YourSecondList);
mergedList.AddRange(YourThirdList);
AddRange is special-cased for ICollection<T> for efficiency.
You can use the Zip method.
one.Zip(two,(o1, o2) => new One()
{
ID = o1.ID,
Name = o1.PCName,
LastName = o1.LName,
MainName = o2.mName
});
var list = dc.Orders.
Join(dc.Order_Details,
o => o.OrderID, od => od.OrderID, <-- what if i have 2 more parameters let say an ID and a REC on both table. ex.: o=> o.OrderID && o.ItemName, od => od.OrderID && od.Itemname then (o, od) but its result is error? is there another way?
(o, od) => new
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
ShipName = o.ShipName,
Quantity = od.Quantity,
UnitPrice = od.UnitPrice,
ProductID = od.ProductID
}).Join(dc.Products,
a => a.ProductID, p => p.ProductID, <-- at this point too?
(a, p) => new
{
OrderID = a.OrderID,
OrderDate = a.OrderDate,
ShipName = a.ShipName,
Quantity = a.Quantity,
UnitPrice = a.UnitPrice,
ProductName = p.ProductName
});
is it possible to use this lambda expression linq query with multiple parameters by joining 3 tables?
--- UPDATE STILL ERROR -- :(
var header = DB.Delivery_HeaderRECs.Join(DB.Delivery_DetailsRECs, <-- Red Line on DB.Delivery_HeaderRECs.Join
q => new { q.drNO, q.RecNO },
qw => new { qw.DrNO, qw.RecNO },
(q, qw) => new
{
DR = q.drNO,
DATE = q.DocDate,
RECNO = q.RecNO,
CUSTID = q.CustomerID,
CUSTADDR = q.CustomerADDR,
RELEASE = q.ReleasedBy,
RECEIVE = q.ReceivedBy,
REMARKS = q.Remarks,
ITEM = qw.ItemCode,
DESC = qw.ItemDesc,
QTY = qw.Qty,
COST = qw.Unit,
PLATENO = qw.PlateNo,
TICKETNO = qw.TicketNo
}).Join(DB.Delivery_TruckScaleRECs,
w => new { w.DR, w.TICKETNO },
we => new { we.DrNo, we.TicketNO },
(w, we) => new
{
DR = w.DR,
DATE = w.DATE,
RECNO = w.RECNO,
CUSTID = w.CUSTID,
CUSTADDR = w.CUSTADDR,
RELEASE = w.RELEASE,
RECEIVE = w.RECEIVE,
REMARKS = w.REMARKS,
ITEM = w.ITEM,
DESC = w.DESC,
QTY = w.QTY,
COST = w.COST,
PLATENO = w.PLATENO,
TICKETNO = w.TICKETNO,
TRANSAC = we.TransactionType,
FWEIGHT = we.FirstWeight,
SWEIGHT = we.SecondWeight,
NWEIGHT = we.NetWeight
}).FirstOrDefault();
I made up changes base on the answer but an error said above the statement:
"The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly". i think it's talking about the parameters i've made..
You can use anonymous type for the Join like this:
var list = dc.Orders.Join(dc.Order_Details,
o => new { o.OrderID, o.ItemName},
od => new { od.OrderID, od.ItemName},
...);
The anonymous type will be compiled to use the autoimplemented Equals and GetHashCode so that the equality will be derived by the equality of all the corresponding properties. Just add more properties as you want in the the new {....}. Note that the order of properties provided in the 2 new {...} should be the same order of correspondence. The names should also be matched, you can explicitly specify the names to ensure this (this is needed in some cases) such as:
new {OrderID = o.OrderID, Name = o.ItemName}
However in your case the property names will be used as the same properties of the item.
UPDATE
This update is just a fix for your specific parameters, I said that the property names should be the same, if they are not you have to explicitly name them like this:
var list = dc.Orders.Join(dc.Order_Details,
q => new {DrNO = q.drNO, q.RecNO},
qw => new {DrNO = qw.DrNO, qw.RecNO},
...);