How can generate a sequence number inside a LINQ select? - c#

I am getting a hard time generating a sequence number for my list using Linq Select.
I tried to use a normal variable i then increment it inside but it's not working.
var grouped = (from x in jOMACDetails
group x by new { x.MAWorkCode, x.ConstructionNumber } into g
let f = g.First()
select new UtilityReceivingReportDetailEntity
{
DefaultAccountCode = string.IsNullOrWhiteSpace(f.AccountTitleCode) ? f.AccountTitleName.Trim() : f.AccountTitleCode.Trim(),
CompanyID = CurrentContext.CurrentCompanyID,
RRNumber = socnumber.Trim(),
RRSequenceNumber = (short)???, // <---- Here is the container the I need to be sequence
//...............
}).AsEnumerable();
can someone help me about this?
thanks in advance

You can try Select() overload which projects each element of a sequence into a new form by incorporating the element's index automatically:
var grouped = jOMACDetails.GroupBy(x => new { x.MAWorkCode, x.ConstructionNumber })
.Select(g => g.First())
.Select((r, index) => new UtilityReceivingReportDetailEntity
{
DefaultAccountCode = string.IsNullOrWhiteSpace(r.AccountTitleCode) ? r.AccountTitleName.Trim() : r.AccountTitleCode.Trim(),
CompanyID = CurrentContext.CurrentCompanyID,
RRNumber = socnumber.Trim(),
RRSequenceNumber = index
})
.AsEnumerable();
Sadly, there is not any query expression which uses that overload. So, I wrote my answer in method syntax. But, you can use .Select after finishing your query expression if you wish. But, IMHO there is no need.

You´re looking for this?
var i = 0;
var grouped = (from x in jOMACDetails
group x by new { x.MAWorkCode, x.ConstructionNumber } into g
let f = g.First()
select new UtilityReceivingReportDetailEntity
{
DefaultAccountCode = string.IsNullOrWhiteSpace(f.AccountTitleCode) ? f.AccountTitleName.Trim() : f.AccountTitleCode.Trim(),
CompanyID = CurrentContext.CurrentCompanyID,
RRNumber = socnumber.Trim(),
RRSequenceNumber = i++
}).AsEnumerable();

Related

Compare 2 lists and reduce quantities of resulting list

I have 2 lists
grpoList
I have a second named assembly
I have the following code
grpoList = grpoList.Where(c => assembly.Exists(cr => cr.ItemCode == c.ItemCode)).ToList();
This returns
How do I amend the code such that the line of DocEntry 393 on the results has a quantity of 2 instead of 4?
You probably want to perform a Join between the list and select the required fields out of it like
var data = grpoList.Join(assembly,
x => x.ItemCode,
y => y.ItemNo,
(x, y) => new
{
DocEntry = x.DocEntry,
LineNum = x.LineNum,
CarCode = x.CarCode,
ItemCode = x.ItemCode,
OpenQty = y.OpenQty,
DocDate = x.DocDate
}).ToList();
we can use linq joins to create the custom outputs:
var query = from c in grpoList
join cr in assembly
on c.ItemCode equals cr.ItemCode
select new
{
c.DocEntry,
c.LineNum,
c.CarCode,
c.ItemCode,
OpenQty = c.OpenQty - cr.OpenQty,
c.DocDate
};
Keeping name c and cr same as your question so that you can understand it easily.

Using linq to group and sum List<int> (Zip?)

I have a list of objects I want to group.
Objects have a List parameter, and during grouping I want to make the sum of the lists like this :
for(int i=0;i<MyList1.Count();i++)
{
StatutOperations[i]=StatutOperations1[i]+StatutOperations2[i]...
}
For now using linq I have the following :
liste_rep = liste_rep.GroupBy(l => l.Nom)
.Select(cl => new Repere
{
Quantite = cl.Sum(c => c.Quantite),
IdAff = cl.First().IdAff,
ID = 0,
ListeOperations = cl.First().ListeOperations,
StatutOperations = cl.Zip(StatutOperations)//First().StatutOperations
}).ToList();
The line making problem is the last one, I found how to use Zip function to summ two tables, but what if I want to use it grouping Lists?
Edit : StatusOperations is a list of integers, concretely liste_rep is a list of details, details have a list of n operations, and StatusOperations determines how much details have been operated for each operation.
Example :
ListOperations = CUT, DRILL, PAINT
StatusOperations = 20,20,10
This means 20 details are cut, 20 are drilled and 10 are painted
I want to group the list of details getting totals for each operation.
Edit 2 :
For now I only could manage to do it making myself the grouping :
liste_rep = liste_rep.OrderBy(p => p.Nom).ToList();
if (liste_rep.Count()>1)
{
totalStatut = liste_rep[0].StatutOperations.ConvertAll(s => s = 0);
string oldRep = "";
Repere repere = new Repere();
foreach (Repere rep in liste_rep)
{
if (rep.Nom!=oldRep)
{
newListRep.Add(repere);
repere = new Repere();
repere.Nom = rep.Nom;
repere.StatutOperations = rep.StatutOperations;
}
else
{
repere.StatutOperations=repere.StatutOperations.Zip(rep.StatutOperations, (x, y) => x + y).ToList();
}
oldRep = rep.Nom;
}
}
You can use this
if StatutOperations is a list of int).
Use this at last line.
StatutOperations= cl.Aggregate((opl1, opl2) =>
{ return opl1.StatutOperations.Zip(opl2.StatutOperations, (opin1,opin2)=>opin1+opin2).ToList(); });
in above code Aggregate runs through two elements and aggregate as sum (op1+op2).
Note : Remember use aggregate if and only if list contains more than one element
.
Edit:
Sorry the above code is incorrect as this is applying aggregate on repere type object and hence the expected return value would be of Repere type.
Edited my code now it should work fine now.
liste_rep.GroupBy(l => l.Nom)
.Select(cl => new Repere
{
Quantite = cl.Sum(c => c.Quantite),
IdAff = cl.First().IdAff,
ID = 0,
ListeOperations = cl.First().ListeOperations,
StatutOperations = cl
.Select(x=>x.StatutOperations)
.Aggregate((x,y)=> x.Zip(y,(p,q)=>p+q).ToList());
}).ToList();

Linq replace column value with another value

Well, im doing a linq query to get a list of results with the same column, and then i need to replace that column value with a new one.
First Code:
var db = GetContext();
var result = from f in GetContext().ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f;
foreach (var item in result)
{
var projectStateHistoryUpdate = db.ProjectStateHistories.Find(item.Id);
projectStateHistoryUpdate.ProjectId = newProjectId;
db.Entry(projectStateHistoryUpdate).State = EntityState.Modified;
}
db.SaveChanges();
I searched for some answers, and i found that i can use Select, and make a new object (Linq replace null/empty value with another value)
Second Code:
var result = (from f in GetContext().ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f).Select(d=> new { Id = d.Id, EventName = d.EventName, LogUser = d.LogUser, ProjectId = newProjectId, TimeStamp = d.TimeStamp });
And even, Third Code:
var db = GetContext();
var result = (from f in db.ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f).Select(d=> new { ProjectId = newProjectId});
But only the First Code works.
I wanted to ask what i am doing wrong, since i think it is better to change the value with a query, instead of using a foreach.
See code below:
var db = GetContext();
(from f in db.ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f)
.ToList()
.ForEach(i => i.ProjectId = newProjectId);
db.SaveChanges();
Alternatively:
var db = GetContext();
db.ProjectStateHistories
.Where(f => f.ProjectId.Equals(oldProjectId))
.ToList()
.ForEach(f => f.ProjectId = newProjectId);
db.SaveChanges();
The shortest way I know of to replace your code is this:
var db = getcontext();
db.ProjectStateHistories
.Where(f => f.ProjectId.Equals(oldProjectId))
.ToList()
.ForEach(f => f.ProjectId = newProjectId);
db.SaveChanges();
Other answers can be found here
I've just had a thought that could help you, I am just free coding here!
If you just put the for each as part of the select, and then save your changes will that work?
foreach (var source in db.ProjectStateHistories.Where(x => x.ProjectId == oldProjectId))
{
source.ProjectId= newProjectId;
db.Entry(source).State = EntityState.Modified;
}
db.SaveChanges();
I think this is a more efficient way of doing it.
Also the .Select() method is only really useful if you need to Project to a view Model, it won't change the variables in the database, just show them in the newly declared object.
Thanks,
Phill

The LINQ expression contains references to queries that are associated with different contexts

Here's my code:
var myStrings = (from x in db1.MyStrings.Where(x => homeStrings.Contains(x.Content))
join y in db2.MyStaticStringTranslations on x.Id equals y.id
select new MyStringModel()
{
Id = x.Id,
Original = x.Content,
Translation = y.translation
}).ToList();
And I get the error that the specified LINQ expression contains references to queries that are associated with different contexts. I know that the problem is that I try to access tables from both db1 and db2, but how do I fix this?
MyStrings is a small table
Load filtered MyStrings in memory, then join with MyStaticStringTranslations using LINQ:
// Read the small table into memory, and make a dictionary from it.
// The last step will use this dictionary for joining.
var byId = db1.MyStrings
.Where(x => homeStrings.Contains(x.Content))
.ToDictionary(s => s.Id);
// Extract the keys. We will need them to filter the big table
var ids = byId.Keys.ToList();
// Bring in only the relevant records
var myStrings = db2.MyStaticStringTranslations
.Where(y => ids.Contains(y.id))
.AsEnumerable() // Make sure the joining is done in memory
.Select(y => new {
Id = y.id
// Use y.id to look up the content from the dictionary
, Original = byId[y.id].Content
, Translation = y.translation
});
You are right that db1 and db2 can't be used in the same Linq expression. x and y have to be joined in this process and not by a Linq provider. Try this:
var x = db1.MyStrings.Where(xx => homeStrings.Contains(xx.Content)).ToEnumerable();
var y = db2.MyStaticStringTranslations.ToEnumerable();
var myStrings = (from a in x
join b in y on x.Id equals y.id
select new MyStringModel()
{
Id = x.Id,
Original = x.Content,
Translation = y.translation
}).ToList();
Refer to this answer for more details: The specified LINQ expression contains references to queries that are associated with different contexts
dasblinkenlight's answer has a better overall approach than this. In this answer I'm trying to minimize the diff against your original code.
I also faced the same problem:
"The specified LINQ expression contains references to queries that are associated with different contexts."
This is because it's not able to connect to two context at a time so i find the solution as below.
Here in this example I want to list the lottery cards with the owner name but the Table having the owner name is in another Database.So I made two context DB1Context and DB2Context.and write the code as follows:
var query = from lc in db1.LotteryCardMaster
from om in db2.OwnerMaster
where lc.IsActive == 1
select new
{
lc.CashCardID,
lc.CashCardNO,
om.PersonnelName,
lc.Status
};
AB.LottryList = new List<LotteryCardMaster>();
foreach (var result in query)
{
AB.LottryList.Add(new LotteryCardMaster()
{
CashCardID = result.CashCardID,
CashCardNO = result.CashCardNO,
PersonnelName =result.PersonnelName,
Status = result.Status
});
}
but this gives me the above error so i found the other way to perform joining on two tables from diffrent database.and that way is as below.
var query = from lc in db1.LotteryCardMaster
where lc.IsActive == 1
select new
{
lc.CashCardID,
lc.CashCardNO,
om.PersonnelName,
lc.Status
};
AB.LottryList = new List<LotteryCardMaster>();
foreach (var result in query)
{
AB.LottryList.Add(new LotteryCardMaster()
{
CashCardID = result.CashCardID,
CashCardNO = result.CashCardNO,
PersonnelName =db2.OwnerMaster.FirstOrDefault(x=>x.OwnerID== result.OwnerID).OwnerName,
Status = result.Status
});
}

String.Split in a Linq-To-SQL Query?

I have a database table that contains an nvarchar column like this:
1|12.6|18|19
I have a Business Object that has a Decimal[] property.
My LINQ Query looks like this:
var temp = from r in db.SomeTable select new BusinessObject {
// Other BusinessObject Properties snipped as they are straight 1:1
MeterValues = r.MeterValues.Split('|').Select(Decimal.Parse).ToArray()
};
var result = temp.ToArray();
This throws an NotSupportedException: Method 'System.String[] Split(Char[])' has no supported translation to SQL.
That kinda sucks :) Is there any way I can do this without having to add a string property to the business object or selecting an anonymous type and then iterating through it?
My current "solution" is:
var temp = from r in db.SomeTable select new {
mv = r.MeterValues,
bo = new BusinessObject { // all the other fields }
};
var result = new List<BusinessObject>();
foreach(var t in temp) {
var bo = t.bo;
bo.MeterValues = t.mv.Split('|').Select(Decimal.Parse).ToArray();
result.Add(bo);
}
return result.ToArray(); // The Method returns BusinessObject[]
That's kinda ugly though, with that temporary list.
I've tried adding a let mv = r.MeterValues.Split('|').Select(Decimal.Parse).ToArray() but that essentially leads to the same NotSupportedException.
This is .net 3.5SP1 if that matters.
You need to force the select clause to run on the client by calling .AsEnumerable() first:
var result = db.SomeTable.AsEnumerable().Select(r => new BusinessObject {
...
MeterValues = r.MeterValues.Split('|').Select(Decimal.Parse).ToArray()
}).ToList();
You can't use split, but in this scenario you can do the following:
// Database value is 1|12.6|18|19
string valueToFind = "19";
var temp = from r in db.SomeTable.Where(r => ("|" + r.MeterValues + "|").Contains("|" + valueToFind + "|"));
This code adds outer pipes (|) to the database value on the fly inside the query so you can do start, middle, and end value matches on the string.
For example, the above code looks for "|19|" inside "|1|12.6|18|19|", which is found and valid. This will work for any other valueToFind.
You don't need to use a temporary list:
var query = from r in db.SomeTable
select new
{
r.Id,
r.Name,
r.MeterValues,
...
};
var temp = from x in query.AsEnumerable()
select new BusinessObject
{
Id = x.Id,
Name = x.Name,
MeterValues = x.mv.Split('|').Select(Decimal.Parse).ToArray(),
...
};
return temp.ToArray();
Unfortunately its the IQueryable you are using (Linq to SQL) that is not supporting the Split function.
You are really only left with the IEnumerable (Linq to Objects) support for it in this case. You second code snippet is what you need to do, or something like...
var temp = (from r in db.SomeTable select new {
mv = r.MeterValues,
bo = new BusinessObject { // all the other fields }
}).AsEnumerable().Select(blah, blah) ;

Categories