Get listitem value - c#

Edit/Update!!!
I wanted to update the question as the answer below only guided me in the right direction but did not completely solve the issue.
However i did manage to fix the problem by changing how items and hopefully this will help someone in the future
Add items to the class list like so
descriptionclb.Items.Add(new listItem { Name = ItemToAdd, Price = Convert.ToDouble(ItemPrice), Quantity = Convert.ToDouble(Quantity.Text) });
And iterate items like so
foreach (Listitem item in descriptionclb.Items)
{
double TotalAmmount = item.Price);
//Do stuff with Item
}
I'm trying to get the value of a list item within a listbox, I keep getting an error "'System.InvalidCastException' Unable to cast object of type 'System.String' to type 'list'."
Any help would be appreciated,and I have tried to do lots of research with no result (Maybe im not phrasing the question right on google). See my code below.
Class ListItem
public class listItem
{
public string Name { get; set; }
public double Price { get; set; }
public double Quantity { get; set; }
public override string ToString()
{
return Name;
}
}
I insert the values here
Globals.li.Name = ItemToAdd;
Globals.li.Price = Convert.ToDouble(ItemPrice);
Globals.li.Quantity = Convert.ToDouble(Quantity.Text);
descriptionclb.Items.Add(Globals.li.ToString());
Globals is a globlal class and li is the listitem li = new listItem
I get the error here
foreach (var item in descriptionclb.Items)
{
double TotalAmmount = Convert.ToDouble(((list)item).Price);
}

You are adding strings here:
descriptionclb.Items.Add(Globals.li.ToString());
So you are saving string rather than listItem object that is why you get the error.
Should be:
descriptionclb.Items.Add(Globals.li);
Also this object descriptionclb.Items should be of type listItem
And the for loop should something like:
foreach (listItem item in descriptionclb.Items)
{
double TotalAmmount = item.Price;
}

In your code you have a type called 'list'. Your foreach loop iterates over a list of strings, therefore 'var item' is a string. You can't convert the 'list' type to a string which is causing the exception.
If you're trying to add all the 'listItem' Price values up then you should try changing the type of 'descriptionclb.Items' from a list of strings to a list of 'listItem' and add the listItem directly. Then you will be able to get rid of the cast.
descriptionclb.Items.Add(Globals.li);
foreach (var item in descriptionclb.Items)
{
double TotalAmmount = item.Price;
}
Just a note; in the for loop you don't do anything with TotalAmmount.

you need to change
descriptionclb.Items.Add(Globals.li);
and
foreach (var item in descriptionclb.Items)
{
double TotalAmmount = item.Price;
}
if TotalAmmount , total fares from list cahnge it to:
double TotalAmmount=0
foreach (var item in descriptionclb.Items)
{
TotalAmmount = TotalAmmount+ item.Price;
}

Related

Can't iterate over ListView Items in Xamarin Forms

When I write this code:
ListView lv = new ListView();
foreach (ListViewDataItem item in lv.Items)
{
}
I get "the type or name ListViewDataItem could not be found"
Items is also not found under the lv object.
Basically I need to iterate through each row of the ListView and set a checkbox added using item template.
How can I accomplish that?
The correct way to loop through a listview is to access it's ItemsSource. Then you can cast the item into your view model and do stuff with it.
foreach (var item in lv.ItemsSource)
{
// cast the item
var dataItem = (ListViewDataItem) item;
// then do stuff with your casted item
...
}
I used a for loop to iterate over my listView ChildCount, assigned a var as the Tag of the GetChildAt as ImageAdapterViewHolder and then set my checkbox to false.
class ImageAdapterViewHolder : Java.Lang.Object
{
public ImageView SavedImage { get; set; }
public TextView Description { get; set; }
public CheckBox SelectImage { get; set; }
}
for (int i = 0; i < listView.ChildCount; i++)
{
var row = listView.GetChildAt(i).Tag as ImageAdapterViewHolder;
row.SelectImage.Checked = false;
}

C# select item of combobox by ID

I have this class
class ComboboxValue
{
public int Id { get; private set; }
public string Name { get; private set; }
public ComboboxValue(int id, string name)
{
Id = id;
Name = name;
}
public override string ToString()
{
return Name;
}
}
and I set my entries like this:
var list = Funktionen.LoadCustomers();
foreach (var item in list)
{
MyCombo.Properties.Items.Add(new ComboboxValue(item.ID, item.Name));
}
In another function, I will set a item in my combobox by customerID.
How can I do this?
Btw. I´m using Devexpress.
Thank you.
To programmatically select a value for the combo, set the ComboBoxEdit.EditValue property. Here is some sample code:
ComboBoxEdit.EditValue = 2; // select an item which ID = 2
Besides the Selected index you can use the SelectedItem property to select any item within the editor's item list. You need to assign an underlying data object to the SelectedItem property.
Alternatively, you can set its EditValue to '25' that is the ValueMember property value of the desirable item as shown in above example.
Reference these:
Select Item in ComboBoxEdit
how set combobox selected value
To select item in ComboboxValue class :
comboBox1.SelectedItem = comboBox1.Items.Cast<ComboboxValue>()
.Where(i => i.Name == dataGridView1.CurrentRow.Cells[5].Value.ToString()).Single();
var item = MyCombo.Properties.Items.FirstOrDefault(i => i.ID == yoursearchIDhere);
item will be combobox item which you want to get. If you look for it or not, let me know and explain clearly please
LoadCustomers() should return List also.
Try
MyCombo.SelectedItem = MyCombo.Items.SingleOrDefault(x => (x as ComboboxValue).Id == externalID)

Foreach in wpf (cannot convert char to string)?

Each time I add an item in the list ListData that I have created I have to check that does not exist.
This is the element:
public ObservableCollection<LabelGroup_RowItem> ListData = new
ObservableCollection<LabelGroup_RowItem>();
public class LabelGroup_RowItem
{
public int ID { get; set; }
public string Name { get; set; }
}
element.Name = TextEdit_GroupName.Text;
foreach (string x in ucLabel.ListData[0].Name)
{
if (x.Equals(element.Name))
{
MessageBox.Show("....");
}
}
How should I do?
While it's hard to know what ucLabel is, you probably meant:
foreach (var x in ucLabel.ListData)
{
if (x.Name.Equals(element.Name))
{
MessageBox.Show("....");
}
}
you can use Linq - this will match if any item in ListData(.Name) matches your text field
string TextToMatch = TextEdit_GroupName.Text;
if(ListData.Any(x => x.Name == TextToMatch))
{
MessageBox.Show(string.format("{0} already exists",TextToMatch);
}
bare in mind this is mostly psuedo, but it should work
about equals metchod
If Name property is unique try to compare it with simple '==' operator.
Also your foreach loop looks wierd. I am not sure if this: ucLabel.ListData[0].Name
is IEnumerable. Maybe you think about
foreach (var x in ucLabel.ListData){
if (x.Name==element.Name) { do something }
}
Also remember to avoid adding or removing ListData content in foreach loop becous it will crash your code.

How to get the sum of List object property values using foreach

What i'm trying to do
Find the price sum for all items in a shoppingcart list.
How i tried to solve it
I think it makes sense to add it as a property in the Cart-class.
I also think it would be logical to just use a foreach loop to iterate the CartList and add the itemprice (ProductsInCart.Price) to a temporary variable (PriceSum), which is returned in "Cart.PriceAllContent" property.
C#
//Instantiating Cart
Cart C2Cart = new Cart();
//Getting Item in cart from Session
C2Cart.TakeCart();
//Writing out result
Response.Write(C2Cart.PriceAllContent);
Classes
public class Cart
{
//FIELDS
private List<ProductsInCart> _cartList;
//PROPERTIES
public List<ProductsInCart> CartList
{
get { return _cartList; }
set { _cartList = value; }
}
public float PriceAllContent
{
get
{
float PriceSum= 0;
foreach (var ProductsInCart in _cartList)
{
PriceSum= +ProductsInCart.Price;
}
return PriceSum;
}
}
...........
}
public class ProductsInCart
{
//FIELDS
private int _id;
private string _name;
private float _price;
private int _amount;
............
}
Complete class code can be seen here (may not be fully updated yet. Ask if needed)
https://github.com/chmodder/PlanteskoleWebsite/tree/master/App_Code
Problem
Problem is, that when writing out the result, It would only write out the last items price instead of the sum of all itemprices.
Response.Write(C2Cart.PriceAllContent);
I allready tried searching for a solution, but couldn't find what i needed.
If anyone can help me solve the problem i would be a happy man.
If you want to increment PriceSum variable with product price, use += operator:
foreach (var ProductsInCart in _cartList)
{
PriceSum += ProductsInCart.Price; // instead of =+
}
When you write = +value then its two separate operators = operator and + operator i.e. +ProductsInCart.Price just returns value of products, price, and then you assign this value to PriceSum. As result, you will have price of last product in list.
You also can use LINQ instead of this loop:
public float PriceAllContent
{
get { return _cartList.Sum(p => p.Price); }
}
The =+ should be += to fix your problem.
You can also simplify:
public float PriceAllContent
{
get { return _cartList.Sum(i => i.Price); }
}
Although as a convention, I'd use a method CalculatePriceAllContent() instead of a property, to signify to the caller that you are doing a calculation and not just getting a stored value. See https://stackoverflow.com/a/601648/1094268
int sum1;
List<int> num = new List<int>() {1,2,3,4,5 };
sum1 = num.Sum();
Console.WriteLine(sum1);

Take the highest bid by this user

I'm building an auction site and the user can bid on the same item more than once (obviously). In the user's dashboard, a user can view his bids. When the user bids on the same item more than once, I want only one entry with the highest bid value to show up. My current code shows an entry for each bid. I tried a few things but I couldn't figure it out. Here's what I've got:
public class Bid
{
public int Id { get; set; }
public double Amount { get; set; }
public DateTime Date { get; set; }
public virtual Item Item { get; set; }
public virtual User User { get; set; }
}
protected override List<ItemForUserBids> ResolveCore(User source)
{
var items = new List<ItemForUserBids>();
var userBids = source.Bids;
foreach (var bid in userBids)
{
var item = bid.Item;
var c = new ItemForUserBids
{
BidValue = bid.Amount,
BidId = bid.Id,
Description = item.Description,
Id = item.Id,
ItemThumb = item.MainImageLink(),
Status = _itemsService.GetBiddingStatus(item, source),
TimeLeft = item.EndDate.TimeLeft(),
Title = item.Title
};
items.Add(c);
}
return items;
}
I tried to get Distinct bids based on the Item.Id but that did not work. Now I'm thinking maybe I could use the Date property of the Bid entity somehow to get to the result I want but my head stopped thinking.
Any suggestions?
UPDATE:
I got it to work using a dictionary and using OrderBy() and Max() like many suggested. But I think the latter could be further improved.
Implementation using a dictionary (works):
var userBids = new Dictionary<string, Bid>();
foreach (var bid in allUserBids)
{
var key = bid.Item.Id.ToString();
if(userBids.ContainsKey(key))
{
if (userBids[key].Amount < bid.Amount)
userBids[key] = bid;
}
userBids[key] = bid;
}
Attempt using the other method (works):
var highestBids =
source.Bids.Where(x => x.Date > DateTime.Now.AddYears(-1))
.GroupBy(x => x.Item.Id,
(itemId, bids) =>
new
{
ItemId = itemId,
MaxBid = bids.Max(x => x.Amount)
}).ToList();
var userBids = new List<Bid>();
foreach (var bid in source.Bids)
{
for(var i = 0; i < highestBids.Count; i++)
{
var curr = highestBids[i];
if (bid.Item.Id.Equals(curr.ItemId) && bid.Amount.Equals(curr.MaxBid)) {
userBids.Add(bid);
highestBids.Remove(curr);
}
}
}
How do I get rid of those loops? And maybe have it all in one chained statement?
The comments posted so far should be a good indication that you should look into re-architecting this a little, but the immediate code solution involves using System.Linq to chain together a GroupBy, Max, and a Select.
you could simply create a dictionary of user bids, where the key is the item id. Then for each user bid if an item id is not already used then add the current bid to the dictionary, if it is used then see if the bid amount of the item that exists in the dictionary already is lower than the current item then replace the existing item in the dictionary with the current one.
However this is very inefficient as really you only want to load the top 1 bid sorted descending by bid amount for each bid id, not load all the bids then work out the highest. What happens if your user has 10,000 old bids? Do they all get loaded?

Categories

Resources