How to replace duplicated value from a table to "quantity"? - c#

Im trying to make a typical webshop, got everything worked out so far, but I got this following issue: How do I replace duplicate database-value in a List to quantity instead, and list them into ListView? E.g. if I add two of same product into my cart, I want to be able to show quantity instead showing two of same product in the cart-list.
PS: Im listing my results in ListView.
(Form_Load for cart):
using (eShopEntities db = new eShopEntities()){
var list = new List<Product>(db.Products.ToList());
var listFilter = new List<Product>();
foreach (var id in list)
{
foreach (var Sessions in SessionData)//got selected products stored in sessions
{
if (id.ID == Sessions)
{
listFilter.Add(id); //Add all selected products(via session)
}
}
}
int TotSum = 0;
foreach (var sum in listFilter)
{
TotSum = TotSum + sum.Price;
}
cartListView.DataSource = listFilter; cartListView.DataBind();
lblSum.Text = TotSum.ToString();
}
Right now, everything is listed in aspx. But Im not sure how to replace duplicated into quantities from listFilter AND send the quanties-data along with the result from listFilter into cartListWiev togheter.
My Product table(SQL): ID(PK), Name, ImagePath, Price, and CatergoryID(FK)
Thanks

As one of possibilities (not obligatory the best one, but technically it should work) you can change your code like that:
using (eShopEntities db = new eShopEntities()){
IDictionary<long, int> productQuantities = new Dictionary<long, int>(); // supposed your product.ID is of type long
var list = new List<Product>(db.Products.ToList());
var listFilter = new List<Product>();
foreach (var id in list)
{
foreach (var Sessions in SessionData)//got selected products stored in sessions
{
if (id.ID == Sessions)
{
if (!productQuantities.ContainsKey(id.ID)) // new
{
listFilter.Add(id); //Add all selected products(via session)
productQuantities.Add(id.ID, 1)
} // new else {
productQuantities[id.ID]++; // new
}
}
}
}
int TotSum = 0;
foreach (var sum in listFilter)
{
// TotSum = TotSum + sum.Price; // old
sum.Quantity = productQuantities[id.ID]; // supposed your class Product has corresponding property for quantities
TotSum = TotSum + sum.Price * sum.Quantity;
}
cartListView.DataSource = listFilter; cartListView.DataBind();
lblSum.Text = TotSum.ToString();
}

Related

How do i add data to a specific column in datagridview?

I have i already made 3 lists of elements that i want to insert on my datagridview,
but the problem is when i try to insert data on my datagrid a receive something like this,
so to insert data i used the following code:
IList<string> ruas = new List<string>();
foreach (var element in Gdriver.FindElements(By.ClassName("search-title")))
{
//ruas.Add(element.Text);
table.Rows.Add(element.Text);
}
IList<string> codps = new List<string>();
foreach(var Codpelement in Gdriver.FindElements(By.ClassName("cp")))
{
table.Rows.Add("",Codpelement.Text);
}
IList<string> Distritos = new List<string>();
foreach (var Distritoelement in Gdriver.FindElements(By.ClassName("local")))
{
//Distritos.Add(Distritoelement.Text);
table.Rows.Add("","",Distritoelement.Text.Substring(Distritoelement.Text.LastIndexOf(',') + 1));
}
Could you kindly, tell me a better way to make the data appear from top to bottom?
Thanks.
The problem is that you enter a single value per row. You should have three rows in total, but you have 3 * numberofcolumns rows. Instead of your current approach I recommend the following:
IList<string> ruas = new List<string>();
foreach (var element in Gdriver.FindElements(By.ClassName("search-title")))
{
ruas.Add(element.Text);
}
IList<string> codps = new List<string>();
foreach(var Codpelement in Gdriver.FindElements(By.ClassName("cp")))
{
codps.Add(Codpelement.Text);
}
IList<string> Distritos = new List<string>();
foreach (var Distritoelement in Gdriver.FindElements(By.ClassName("local")))
{
Distritos.Add(Distritoelement.Text.Substring(Distritoelement.Text.LastIndexOf(',') + 1));
}
for (int i = 0; i < ruas.Count; i++) {
table.Rows.Add(ruas.ElementAt(i), codps.ElementAt(i), Distritos.ElementAt(i));
}

How i foreach loop in listitems values entity framework

I have 2 lists. One has 3 records like 1 , 2 , 3 and seconds list holds table records. All i wanna do add first list values to second list.
I hope helps.
foreach (var itemAgent in listofValues)
{
foreach (var item in formSorgu)
{
#region MyRegion
CrmDonusleri crmEkleme = new CrmDonusleri()
{
AradigiBolge = item.bolge,
AramaTarihi = Convert.ToDateTime(item.aratarihi),
Musno = item.musno,
GeriDonusYapildiMi = false,
AtanmaTarihi = DateTime.Now,
KanalAdi = item.kanal,
ProgramAdi = item.program,
AtananAgent = itemAgent
};
DbContext.CrmDonusleri.Add(crmEkleme);
#endregion
}
}
DbContext.SaveChanges();
listofValues hold 3 records and formSorgu hold 2000 records. listofValues as List One and formSorgu as List Two. And i want my final list like Picture below.
I don't think my code is right. Please show me the right way to write this query.
for (int i = formSorgu.Count + 1; i >= 0; i--)
{
foreach (var itemAgent in listofValues)
{
CrmDonusleri crmEkkle = new CrmDonusleri()
{
Musno = formSorgu.FirstOrDefault().musno,
AtananAgent = itemAgent
};
}
}
when i use this code it gets one record from formSorgu but add to listofValues 3 times i just want it to foreach one time and go out from foreach loop and carry on other for loop record.
actually, i love to share i am not like stackover mods. so i found an excellent answer on internet. you can find a link that equally selecting items from list and psuedo run.
solution link
that is a link i used. and i turn my code like this;
var randoAgent = new RandomPicker<string>(listofValues);
foreach (var itemSorgu in formSorgu)
{
var item = randoAgent.PickItem();
CrmDonusleri crmEkle = new CrmDonusleri()
{
Musno = itemSorgu.musno,
TelNo = itemSorgu.telno,
AtananAgent = item,
AradigiBolge = itemSorgu.bolge,
AramaTarihi = Convert.ToDateTime(itemSorgu.aratarihi),
AtanmaTarihi = DateTime.Now,
Ekleyen = itemSorgu.ekleyen,
GeriDonusYapildiMi = false,
KanalAdi = itemSorgu.kanal,
ProgramAdi = itemSorgu.program
};
DbContext.CrmDonusleri.Add(crmEkle);
}
DbContext.SaveChanges();
and works perfect.

Entity Framework: How to insert data while looping through multiple lists

I am attempting to insert data from two List.
I am able to successfully insert from one List but adding the second list using a foreach loop does not work as expected.
How do I loop through each of these list so that I can insert their values?
Code:
private void InsertList()
{
var listA = new List<string>();
var listB = new List<string>();
//Populate both list by splitting items in listbox
foreach (ListItem item in ListBox1.Items)
{
var components = item.Value.Split('/');
listA.Add(components.First());
listB.Add(components.Last());
}
using (DataContext dataContext = new DataContext())
{
foreach (var itemA in listA)
{
foreach (var itemB in listB)
{
LIST_OBJECTS listObject = new LIST_OBJECTS
{
LIST_ITEM_A = itemA,
LIST_ITEM_B = itemB
};
dataContext.LIST_OBJECTS.Add(listObject);
}
}
dataContext.SaveChanges();
}
}
What about a for loop?
for (var i = 0; i < listA.Count; i++)
{
LIST_OBJECTS listObject = new LIST_OBJECTS
{
LIST_ITEM_A = listA[i],
LIST_ITEM_B = listB[i]
};
dataContext.LIST_OBJECTS.Add(listObject);
}
Since you know from the creation of the Lists that they'll have the same number of elements, this is fine.
You can do it with LINQ
LIST_OBJECTS listObject = listA.Join(listB,
a=>listA.Indexof(a),
b=>listB.Indexof(b),
(a,b)=> new LIST_OBJECTS()
{
LIST_ITEM_A =a,
LIST_ITEM_B =b
}).ToList();

Filtering a list in c#

So i have two lists .One is an Attorney object list and the other is a list with GUID .I am first just filling the GUID list with values and then looping through it and then matching it to the ID field of Attorney object to get the Attorney's with the given ID .
Is there a nicer way than my try to achieve this.
List<Attorney> Attorneys = msg.CaseDocument.Attorneys;
List<Attorney> CaseDefendantAtt = new List<Attorney>();
List<Guid> AttorneyID = new List<Guid>();
foreach (var s in msg.CaseDocument.Defendants)
{
AttorneyID.AddRange(s.Attorneys);
}
foreach (var p in AttorneyID)
{
var z = Attorneys.FindAll(o => o.AttorneyId == p);
if (z != null)
{
CaseDefendantAtt.AddRange(z);
}
}
How about...
var caseDefendantAtt = msg.CaseDocument.Attorneys.Where(o =>
msg.CaseDocument.Defendants.SelectMany(d => d.Attorneys).Contains(o.AttorneyId));
Try this
var allAttorneyIds = msg.CaseDocument.Defendants.SelectMany(x=> x.Attroneys);
var caseDefendantsAtt = msg.CaseDocument.Attorneys.Where(x=> allAttorneyIds.Contains(x.AttorneyId)).ToList();
Maybe you could store your Attorneys in a Dictionary of [Guid, Attorney], then looking for each Guid in Dictionary.
Dictionary<Guid, Attorney> Attorneys = CreateDictionaryFrom(msg.CaseDocument.Attorneys);
List<Attorney> CaseDefendantAtt = new List<Attorney>();
List<Guid> AttorneyID = new List<Guid>();
foreach (var s in msg.CaseDocument.Defendants)
{
AttorneyID.AddRange(s.Attorneys);
}
foreach (var p in AttorneyID)
{
var z = Attorneys[p];
if (z != null)
{
CaseDefendantAtt.Add(z);
}
}
It will increase the performance with the x1000 factor. But you should notice that we assume there is only one attorney per Guid.
Without using a dictionary, we could improve your search in list seeking for FirstOrDefault instead of FindAll

select value from array at desired index using LINQ

i have an array which have 5 values from index 0 to 4. i want to store the values in my 5 model properties.
public IEnumerable<fields> ConvertTList(List<string[]> rows)
{
var tList = new List<fields>();
foreach (var item in rows)
{
var ListReading = new fields
{
//model properties names are:
// date, user,campaign,adgroup,changes
};
tList.Add(ListReading);
}
return (tList);
}
this is my code when foreach is executed item get 5 values. i want to store the values in model. how i can i store them using linq
Maybe you mean something like this:
public IEnumerable<fields> ConvertTList(List<string[]> rows)
{
return rows.Select(x => StringsToField(x));
}
fields StringsToField(string[] source)
{
return new fields
{
date = source[0],
user = source[1],
campaign = source[2],
adgroup = source[3],
changes = source[4],
};
}

Categories