I have the following problem: I want to check if the reservation number already exists in my listview.
I have the following code to add a reservation to the listview.
reservations.Add(new Reservation(nameTextbox.Text, lastnameTextBox.Text, gendercomboBox.SelectedText, Convert.ToInt32(ageNumericUpDown.Value), Convert.ToInt32(kamercomboBox.SelectedIndex) + 1, Convert.ToInt32(quantityUpDown.Value), true));
reserveringListView.Items.Clear();
foreach (Reservation reservation in reservations)
{
if (!reserveringListView.Items.Contains(reservation.roomnumber))
{
ListViewItem livi = new ListViewItem(reservation.name);
livi.SubItems.Add(reservation.lastname);
livi.SubItems.Add(Convert.ToString(reservation.gender));
livi.SubItems.Add(Convert.ToString(reservation.age));
livi.SubItems.Add(Convert.ToString(reservation.quantity));
livi.SubItems.Add(Convert.ToString(reservation.roomnumber));
reserveringListView.Items.Add(livi);
}
else
{
MessageBox.Show("Its impossible to reserve")
}
}
When i try to test this code i get the following error: Cannot convert from int to System.Windows.Forms.ListViewItem
You should change your if statement, because you check if ListView.Items contains int. You can't do this and, also, inside if you add roomnumber as string (but you check if it is in ListView.Items as int). Your if statement should be:
if (!reserveringListView.Items.Cast<ListViewItem>().Any((i) => i.SubItems[5].Text == Convert.ToString(reservation.roomnumber)))
Maybe I made mistake with index in SubItems. You should check it and if there is mistake write a comment please.
You are getting the error because you are giving the .Contains method an int parameter, while it only accepts a ListViewItem as parameter
try something like:
if (!reserveringListView.Items.Any(litem => litem.SubItems[5].Value == reservation.roomnumber))
{
}
List<T>.Contains(docs) method expects an argument of type T (System.Windows.Forms.ListViewItem) in your case. But you try to pass an int to that method. Thats why you get the error.
In your case I would create a HashSet<int> and store reservation.roomnumber in it, so you can look up next time, if the roomnumber is already there.
Example:
reserveringListView.Items.Clear();
HashSet<int> roomCheck = new HashSet<int>();
foreach (Reservation reservation in reservations)
{
if (roomCheck.Add(reservation.roomnumber))
{
...
}
}
EDIT: added an example
Related
i have a listview with 3 columns (id , name, author), i use this method to add row:
public void addToLv(Book book)
{
//TODO: Verifier si l'item existe avant d'ajouter
ListViewItem lvi1 = new ListViewItem(book.id.ToString());
lvi1.Text = book.id.ToString();
lvi1.SubItems.Add(book.name);
lvi1.SubItems.Add(carte.author);
listView1.Items.Add(lvi1);
}
Now i wan't to check if book exists before i insert the new one to avoid duplicate element, i try this code but it'S not working
i have use this line but it's not working:
(listView1.Items.ContainsKey(book.id))
{
listView1.Items.Add(lvi1);
}
Can you help me please? thank you
From MSDN:
The key comparison is not case-sensitive. The Name property corresponds to the key for a ListViewItem in the ListView.ListViewItemCollection.
So, you have to set the Name in order to use ContainsKey
lvi1.Name = book.id.ToString();
And then the rest like you did:
if (!listView1.Items.ContainsKey(book.id.ToString()))
{
listView1.Items.Add(lvi1);
}
I think you missed a "!" (not) in your code.
(!listView1.Items.ContainsKey(book.id))
{
listView1.Items.Add(lvi1);
}
Your code is saying that if your listview contains that key, you will add another entry that has that key. But it seems you want to do the opposite, right? If your listview does not contain an entry with that key, you want to add an entry that has that key.
It looks like you are storing your individual names on the SubItems property, so you'll need to query that to see if a given book name is present. You can do this using a bit of LINQ as follows:
// If your ListView doesn't contain any items that have a given book as a SubItem
// then add one
if (!listView1.Items.Any(i => i.SubItems.ContainsKey(book.Name))
{
listView1.Items.Add(lvi1);
}
Since your edit indicates that you actually want to check for the ID instead, which is stored at the ListItem-level, then you would just need to slightly adjust your condition to check the Text property since the ListViewItem(string) constructor sets the Text property by default:
if (!listView1.Items.Any(i => i.Text == book.id))
{
listView1.Items.Add(lvi1);
}
If any thing works, try this:
public void addToLv(Book book)
{
//TODO: Verifier si l'item existe avant d'ajouter
ListViewItem lvi1 = new ListViewItem(book.id.ToString());
//lvi1.Text = book.id.ToString();
lvi1.SubItems.Add(book.name);
lvi1.SubItems.Add(carte.author);
if (!existChecker(book.id.ToString()))
listView1.Items.Add(lvi1);
}
private bool existChecker(string id)
{
bool exist = false;
for (int i = 0; i < lvi1.Items.Count && exist != true; i++)
{
if (lvi1.Items[i].SubItems[0].Text == id)
exist = true;
}
return exist;
}
LINQ can't be used for this:
if (!listView1.Items.Any(i => i.SubItems.ContainsKey(book.Name))
The only real way of doing it is to use the search functionality as thus:
if (listView1.FindItemWithText(book.Name) != null)
{
// Do the business...
}
etc...
I need to find a way to use a for-loop to find how many strings that are the same word in the same array-list. I need to use the for-loop because everytime it loops and finds another word that is the same I want to add it to an int variable :the following is the code that have tried to use but it didn;t work. variable bedrooms kept saying that it is 0 when it is not
foreach (string row in RoomType) // RoomType is the ArrayList
{
if (row.Equals("Bedroom"))
{
bedrooms++;
}
}
This code works, which is based on your code. I am assuming that you are probably doing something in your code where bedrooms is getting re-declared during the looping. This is a guess though.
var RoomType = new ArrayList();
var bedrooms = 0;
RoomType.Add("workflow");
RoomType.Add("Bedroom");
RoomType.Add("Bedroom");
foreach (string row in RoomType) // RoomType is the ArrayList
{
if (row.Equals("Bedroom"))
{
bedrooms++;
}
}
Console.WriteLine(bedrooms);
A different way:
var row = RoomType.Cast<string>().ToArray();
var count = row.Aggregate(0, (c, i) => (i.Equals("Bedroom")) ? ++c : c);
If you are not compelled to use a loop, you could try starting with this:
int bedrooms = RoomType.ToArray().Count(row => row.Equals("Bedroom"));
If you are compelled to use a loop, then please post a bit more of the code so that we can see where and how these objects are being set.
I've made a list and, in certain circumstances, the list is populated. Simple. However, when I try to filter the list based on a dropdown selection ddlLeadCounty.SelectedItem.Value, the count comes back as 0. This is definitely not true as I have manually checked that both the value in the dropdown and the value pulled into the list are the same.
Could any of you wise people see where it may be going wrong? I have tried both of the following methods to the same result.
c# .net code behind
myList = myList.FindAll(delegate(Partner part)
{
return part.RegionId.Equals(ddlLeadCounty.SelectedItem.Value);
});
OR
myList = myList.Where(c => c.RegionId.Equals(ddlLeadCounty.SelectedItem.Value)).ToList();
Partner List:
public class Partner
{
public int LeadOppCount;
public string Guid;
public int RegionId;
public Partner(int LeadOppCount, string Guid, int RegionId)
{
this.LeadOppCount = LeadOppCount;
this.Guid = Guid;
this.RegionId = RegionId;
}
}
Dropdown list example:
<asp:ListItem value="100000004">Berkshire</asp:ListItem>
In my tests, at least 1 list item definitely has a regionId of 100000004.
Many thanks in advance.
Considering that you're I see RegionId, I suppose it's a integer, so write something like this a pseudocode:
int valueSelected = (int)ddlLeadCounty.SelectedItem.Value;
myList.FindAll(x=>x.RegionId == valueSelected );
In other words do not use Equals, for possibly boxed value in SelectedValue, but use concrete type.
Should work for you.
The problem is that SelectedIndex.Value is a string value not an int so you will have to parse it. The following line should work:
var myListFiltered = myList.Where(c => c.RegionId.Equals(int.Parse(ddlLeadCounty.SelectedItem.Value))).ToList();
I have generic list already filled with values, I need to sort items, that first value should appear same as query string. Is it possible to compare and sort this values, I'm trying with no success.
Bit updating my question.
For example I have Id: 1,2,3,4,5, and I opened page with Id=5, so I need on my searchResult, to pass 4 as first item in the list.
This code for me worked fine and showing 5 as first item, but I need to force for example p2.ObjectId pass as string value just for example "4294", and object with this Id should appear first:
Sort(searchresult);
static void Sort(List<CollectionsItem> list)
{
list.Sort((p1, p2) => string.Compare(p2.ObjectId, p1.ObjectId, true));
}
Doesn't sound like you want a sort at all.
If you want to put X at the top it's just
var item = MyList[MyList.IndexOf(Target)];
MyList.Remove(item);
MyList.Insert(item,0);
If you want Target at the top and the rest sorted by objectid
Find it, remove it, sort the rest and insert it at zero...
It sounds like you want to compare the value of the property ObjectId as a number instead of a string. Here is my suggestion:
static void Sort(List<CollectionsItem> list)
{
list.Sort((p1, p2) =>
{
if (int.Parse(p1.ObjectId) == int.Parse(p2.ObjectId))
return 0;
else if (int.Parse(p2.ObjectId) > int.Parse(p1.ObjectId))
return 1;
else
return -1;
});
}
I am trying to read a file and process using LINQ.
I have a exclude list where if i encounter certain words in the file, i should omit that line
my code is
string sCodeFile = #"C:\temp\allcode.lst";
List<string> sIgnoreList = new List<string>() { "foo.c", "foo1.c" };
var wordsPerLine = from line in File.ReadAllLines(sCodeFile)
let items = line.Split('\n')
where !line.Contains(sIgnoreList.ToString())
select line;
foreach (var item in wordsPerLine)
{
console.WriteLine(item);
}
My LST file looks like below
\voodoo\foo.c
\voodoo\voodoo.h
\voodoo\std.c
\voodoo\foo1.h
in the end i want only
\voodoo\voodoo.h
\voodoo\std.c
How can i process the ignored list in contains? with my above code i dont get the desired output for sure
can any one help?
regards,
Karthik
Revised my answer. The bug is that you're doing a ToString on the ignore list, which certainly will not work. You must check each item in the list, which can be done using something like this:
where !sIgnoreList.Any(ignore => line.Contains(ignore))
A curiosity: since the above lambda is just passing a value into a method that only take the value as a parameter, you can write this even more compact as a method group like this:
where !sIgnoreList.Any(line.Contains)
Try this.
string sCodeFile = #"C:\temp\allcode.lst";
List<string> sIgnoreList = new List<string>() { "foo.c", "foo1.c" };
var wordsPerLine = File.ReadAllLines(sCodeFile).Where(n =>
{
foreach (var ign in sIgnoreList)
{
if (n.IndexOf(ign) != -1)
return false;
}
return true;
});
It passes the current element (n) to a lambda function, which checks it against every element of the sIgnoreList. Returning false means the element is ignored, true means it's returned.
Change it to:
where !sIgnoreList.Contains(line)
You need to compare each single line and check that it doesn't exist in the ignore list.
That's why the Vladislav's answer did not work.
Here's the working solution:
var result = from line in File.ReadAllLines(codeFile)
where !ignoreList.Any(line.Contains)
select line;
The problem was you didn't want to check for the whole path and messed up words/lines part a bit.