Converting dynamic row into column in linq - linq

var Getitems = (from u in db.EmailSettings
join s in db.SecurityRoles on u.SecurityRoleID equals s.SecurityRoleID
group u by new { u.SecurityRoleID,s.SecurityRoleName} into g
select new
{
TransTypeId = (from v in db.EmailSettings
//join s in db.SecurityRoles on v.SecurityRoleID equals s.SecurityRoleID
where v.SecurityRoleID == g.Key.SecurityRoleID
select new
{
//username = s.SecurityRoleName,
trans = v.TransTypeID
}),
SecurityRoleName=g.Key.SecurityRoleName,
SecurityRoleId=g.Key.SecurityRoleID,
}).ToList();
For example in TransTypeId i have 3 rows of data .. i want to convert tat to single row like SecurityRoleName ,SecurityRoleId,Row1,row2,row3..
where TransTypeId can have any no of rows .. do any one help me to get the desired result
i want the result as the above screen

var Getitems = (from u in db.EmailSettings
join s in db.SecurityRoles on u.SecurityRoleID equals s.SecurityRoleID
group u by new { u.SecurityRoleID,s.SecurityRoleName} into g
select new
{
TransTypeId = (from v in db.EmailSettings
//join s in db.SecurityRoles on v.SecurityRoleID equals s.SecurityRoleID
where v.SecurityRoleID == g.Key.SecurityRoleID
select new
{
//username = s.SecurityRoleName,
trans = v.TransTypeID
}),
SecurityRoleName=g.Key.SecurityRoleName,
SecurityRoleId=g.Key.SecurityRoleID,
}).ToList();
After that you can get the above result by creating a new list in every for each loop by using transactiontypenames = new List() like below code
List<transactiontypename> transactiontypenames;
transactiontypename transactiontypenameobj;
foreach (var x in Getitems)
{
transactiontypenames = new List<transactiontypename>();
objsecurityVM = new SecurityRoleVM();
objsecurityVM.User = x.SecurityRoleName;
objsecurityVM.SecurityRoleId = x.SecurityRoleId;
foreach (var y in x.TransTypeId)
{
transactiontypenameobj = new transactiontypename();
transactiontypenameobj.Transtypes = y.trans;
transactiontypenames.Add(transactiontypenameobj);
}
objsecurityVM.TransTypes = transactiontypenames;
objlistsecurityroleVM.Add(objsecurityVM);
}
objEmailSetting.TableData = objlistsecurityroleVM;
return View(objEmailSetting);
Hope it will be useful for you

Related

How to convert LINQ query to work with EF Core

I'm converting from EF6 to EF Core 3.1 and this LINQ query is failing with a runtime exception stating 'The LINQ expression ... could not be translated.
The group by is what is causing the issue, but I'm not sure how to rewrite it to work with EF Core and keep the result in a nested list.
Notification notification = new Notification()
{
ProductReminders = new List<List<ProductNotification>>(),
ProductStats = new List<StatResult>()
};
var profileCode = 123;
notification.ProductReminders =
(from ng in ProductNotification
where ng.UserProfileCode == profileCode
orderby ng.EndDate ?? DateTime.MaxValue
group ng by ng.GroupGUID into groupG
select (from pn in ProductNotification
join p in Product on pn.ProductID equals p.ProductID
where pn.UserProfileCode == profileCode
&& pn.GroupGUID == groupG.Key
orderby pn.EndDate ?? DateTime.MaxValue
select new ProductNotification()
{
ProductDetail = new ProductDetail()
{
ProductId = pn.ProductID ?? 0,
Upc = p.UPC,
Brand = p.Description,
Manufacturer = p.Name,
ProfileCode = p.ProfileCode,
},
EndDate = pn.EndDate,
NotificationId = pn.NotificationID,
Status = pn.Status,
GroupGuid = pn.GroupGUID
})
.ToList())
.ToList();
Since grouping operator has limitations, I would suggest to read all needed data and provide grouping on the client side. Query in your case will be much effective:
// select only needed data from database
var minimalRequiredData =
from pn in ProductNotification
join p in Product on pn.ProductID equals p.ProductID
where pn.UserProfileCode == profileCode
select new ProductNotification
{
ProductDetail = new ProductDetail
{
ProductId = pn.ProductID ?? 0,
Upc = p.UPC,
Brand = p.Description,
Manufacturer = p.Name,
ProfileCode = p.ProfileCode,
},
EndDate = pn.EndDate,
NotificationId = pn.NotificationID,
Status = pn.Status,
GroupGuid = pn.GroupGUID
};
// materialize result
var materialized = minimalRequiredData.ToList();
// form required result shape using IEnumerable<T>
var resultQuery =
from m in materialized
orderby ng.EndDate ?? DateTime.MaxValue
group m by new m.GroupGUID into g
select g.Orderby(x => x.EndDate ?? ng.EndDate).ToList();
notification.ProductReminders = resultQuery.ToList();

Filtering data from 2 table

Here I have 2 query variable for showing a different type of data,But i want to extract a particular data from first query ,which don't have reference in second query
I have the following code,but it does not work properly as.first query variable is used to join 4 table like A,B,C,D and Second Query variable Join table A and B.Here i want a data from First variable and it don't have any reference in second table
public List<ProductEntityList> GetProductListRegister()
{
var ProductList1 = new List<ProductEntityList>();
var ProductList = new List<ProductEntityList>();
var finalList = new List<ProductEntityList>();
try
{
using (HabitGreen01Entities ob = new HabitGreen01Entities())
{
var list1 = from ctr in ob.TblCreateUsers
join shp in ob.TblShopMasters
on ctr.id equals shp.Fk_CreateUser_Id
join prd in ob.TblProductMaster01
on shp.id equals prd.FK_ShopMaster_Id
select new ProductEntityList
{
Id = prd.id,
Name = prd.Name,
ShopName = shp.Name,
UserName = ctr.Name
};
ProductList1 = list1.ToList();
var temp = from pd in ob.TblProductMaster01
join cr in ob.TblAccountSettings
on pd.id equals cr.f_productmaster01Id
select new ProductEntityList
{
Id = (int)cr.f_productmaster01Id,
Name=pd.Name
};
ProductList = temp.ToList();
var temp1 = from item in ProductList1
where !ProductList.Contains(x=>item.Id)
select new ProductEntityList
{
Id = item.Id,
Name = item.Name,
ShopName = item.ShopName,
UserName = item.UserName
};
finalList = temp1.ToList();
// var temp1= ProductList1.Select(f=>f.Id).Intersect(ProductList.Select(b=>b.Id));
//finalList = matches.ToList();
}
}
catch (Exception e)
{
throw e;
}
return (finalList);
}
Try this:
var temp1 = from item in ProductList1
where !ProductList.Select(c=>c.Id).Contains(item.Id)
select new ProductEntityList
{
Id = item.Id,
Name = item.Name,
ShopName = item.ShopName,
UserName = item.UserName
};
You can write directly:
var finalList = (from item in ProductList1
where !ProductList.Select(c=>c.Id).Contains(item.Id)
select new ProductEntityList
{
Id = item.Id,
Name = item.Name,
ShopName = item.ShopName,
UserName = item.UserName
}).ToList();
var result = ProductList1.Where(p => !ProductList.Any(p2 => p2.Id== p.Id));
finalList = result.ToList();

linq query for update more than one record

I have a table named industries. In this my fields are
workfor_id,
workfor_usr_id,
workfor_industry_id.
With the same values of workfor_id, I have different workfor_industry_id's.
foreach (var k in us){
var ind = dbContext.industries.Where(i => i.workfor_id ==
k.id).Select(i => i).FirstOrDefault();
string ind2 = k.industry;
var industryParts = ind2.Split(',');
var o = (industryParts.Length);
for (c = 0; c < o; c++){
ind.workfor_id = Convert.ToInt16(k.id);
ind.workfor_industry_id = Convert.ToInt16(k.industryid); }
}
To update workfor_industry_id field I have implemented inner loop inside the foreach loop to get the values of workfor_industry_id's.here same record is over loading with different workfor_industry_id's.
can you tell me how to implement this.
UPDATED
This update adds a little more error checking and assumes that -1 is never a valid value for industry_id
short GetShort(string value) {
short returnValue;
value = (value ?? string.Empty).Replace("\"",null);
return short.TryParse(value, out returnValue) ? returnValue : (short)-1;
}
foreach (var k in us){
var id=Convert.ToInt16(k.id);
var toRemove=from i in dbContext.industries
where i.workfor_id == k.id
select i;
var toAdd = from x in (k.industry ?? string.Empty).Split(',')
select new Industry {
workfor_id=id,
workfor_industry_id=GetShort(x)
};
dbContext.industries.DeleteAllOnSubmit(toRemove);
dbContext.industries.InsertAllOnSubmit(toAdd.Where(x=>x.workfor_industry_id != -1));
}
dbContext.SubmitChanges();

group by base on 2 element

equal this
select id,name, count(*) from table group by id, name
what is in linq???
In case of entity framework it is better to return computed projection directly from SQL:
var query = from x in context.YourEntities
group x by new { x.ID, x.Name } into y
select new
{
y.Key.ID,
y.Key.Name,
y.Count()
};
This will do Count in database and reduce amount of transferred data.
var groups = table.GroupBy(elt => new {ID = elt.ID, Name = elt.name});
foreach (var group in groups)
{
var ID = group.Key.ID;
var name = group.Key.Name;
var count = group.Count();
...
}

DataTable linq query iteration

I want to Enumerate Linq Query. Below i specified example.
EX:
DataTable _slidingDataTable = new DataTable("test");
for(int i=0; i<5;i++)
{
DataRow row = _slidingDataTable.NewRow();
startPosition = DateTime.Now;
for(int i=0; i<5;i++)
{
_slidingDataTable.Columns.Add("TransferTime");
row[columnName] = startPosition ;
_slidingDataTable.Columns.Add("TransferData");
row[columnName] = "Test"+i;
}
_slidingDataTable.Rows.Add(row);
}
var query1 = from myRow in _slidingDataTable.AsEnumerable()
where myRow.Field<DateTime>("TransferTime") == startPosition
select myRow;
This query output should be collection of rows. How to get collection row & iterate.
In your context, query1 is an EnumerableRowCollection<DataRow> because you used _slidingDataTable.AsEnumerable(), and you can iterate over it like so :
foreach (DataRow row in query1)
{
// Do stuff with that row
}
I'm giving you an example by which you can see it and it also includes sum in groupby.
var drdatedisp = from row in dtfullreport.AsEnumerable()
group row by row.Field<string>("Order_Date") into g
select new
{
Order_Date = g.Key,
totalQnty = g.Sum(a => a.Field<int>("Item_Quantity")),
totalTax = g.Sum(a => float.Parse(a.Field<decimal>("TAXAMT").ToString())),
totalAmt = g.Sum(a => float.Parse(a.Field<decimal>("VALAMT").ToString()))
};
DataTable dtdatedisp = new DataTable();
dtdatedisp.Columns.Add("Order_Date");
dtdatedisp.Columns.Add("Item_Quantity");
dtdatedisp.Columns.Add("TAXAMT");
dtdatedisp.Columns.Add("VALAMT");
dtdatedisp.Rows.Clear();
foreach (var g in drdatedisp)
{
DataRow newRow1 = dtdatedisp.NewRow();
newRow1[0] = g.Order_Date;
newRow1[1] = g.totalQnty;
newRow1[2] = String.Format("{0:0.00}", g.totalTax);
newRow1[3] = String.Format("{0:0.00}", g.totalAmt);
dtdatedisp.Rows.Add(newRow1);
}

Resources