In C# windows application, I am comparing two different string arrays and depending on which array size is big, I add or delete items to a list view box. using the below code I am able to add to list view without any issues, but I am not able to remove from it.
I get an error that says.
"Error CS1503, Argument 1: cannot convert from 'string' to 'System.Windows.Forms.ListViewItem'"
Here is an excerpt from my code
string[] currentFilesList = GetFileList();
if (currentFilesList.Length > prevFilesList.Length)
{
var addedList = currentFilesList.Except(prevFilesList).ToArray();
foreach (var item in addedList)
{
listView1.Items.Add(item);
}
}
if (currentFilesList.Length < prevFilesList.Length)
{
var removedList = prevFilesList.Except(currentFilesList).ToArray();
foreach (string item in removedList)
{
listView1.Items.Remove(item); //I get error here on "item" Argument 1: cannot convert from 'string' to 'System.Windows.Forms.ListViewItem'"
}
}
prevFilesList = currentFilesList;
I tried both string and var but same result.
you can remove item by
foreach (string item in removedList)
{
var toRemove =listView1.Items.Find(item);
if (toRemove != null)
{
listView1.Items.Remove(toRemove);
}
}
or you can use RemoveByKey
foreach (string item in removedList)
{
listView1.Items.RemoveByKey(item);
}
You can try this by using linq
var newlist = listView1.Cast<ListViewItem>().Where(p=>p.Text.Contains("OBJECT")).ToList().ForEach(listBox1.Items.Remove);
Related
After accessing the local file, I need to check and add the missing column (walmart) before converting it to xml. I confirm data is available in the csv file.
Currently I am getting an error
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute
Code:
string[] vs = File.ReadAllLines(#"C:/Users/Raw.csv");
var lines = new List <String>();
lines = vs.ToList();
foreach (var check in lines)
{
if (!check.Contains("Walmart"))
{
lines.Insert(0,"Walmart");
}
}
foreach (var shw in lines)
{
Console.WriteLine(shw);
}
Techically, if you want just amend your current code you can count how many Walmarts we should add:
var lines = File
.ReadLines(#"C:/Users/Raw.csv")
.ToList();
int walmartsToAdd = 0;
foreach (var check in lines)
if (!check.Contains("Walmart"))
walmartsToAdd += 1;
if (walmartsToAdd > 0)
lines.InsertRange(0, Enumerable.Repeat("Walmart", walmartsToAdd));
foreach (var shw in lines)
Console.WriteLine(shw);
But it seems, that you should modify lines: abc,def => Walmart,abc,def. If it's your case you can just add Select
var lines = File
.ReadLines(#"C:/Users/Raw.csv")
.Select(line => line.StartsWith("Walmart,") ? line : $"Walmart,{line}")
.ToList();
foreach (var shw in lines)
Console.WriteLine(shw);
You can't modify the source Enumerable while iterating on it. I always imagine that the enumerator has inside a current index and if for example, the change would delete all the members the index wouldn't make any sense anymore. The easy solution is to iterate on something else / make a copy.
Here instead of lines you can try iterating on the variable 'vs'.
var vs = File.ReadAllLines(#"C:/Users/Raw.csv");
var lines = vs.ToList();
foreach (var check in vs)
{
if (!check.Contains("Walmart"))
{
lines.Insert(0, "Walmart");
}
}
foreach (var shw in lines)
{
Console.WriteLine(shw);
}
In the code below, .Contains() only return string that start with the text I type in the TextBox. I want it to return all records that contain that string anywhere in the the searched field. Please advise how I can get Contains() to return the value, alternate ways are welcome as well
Thanks
using (var GC = new GroundCommanderEntities())
{
foreach (var Current in GC.IMF_Extensions.Where(filter => filter.Description.Contains(Search_txt.Text) ))
{
string sss = Current.Description;
Coll.Add(sss);
}
// tried same result foreach (var Current in GC.IMF_Extensions.Where(filter => filter.Description.Contains(Search_txt.Text.Trim()) || filter.Description.StartsWith(Search_txt.Text) || filter.Description.EndsWith(Search_txt.Text)))
// tried same result foreach (var Current in GC.IMF_Extensions.Where(filter => filter.Description.Contains(Search_txt.Text.Trim()) ))
}
Try a simpler method without Linq:
using (var GC = new GroundCommanderEntities())
{
foreach (var Current in GC.IMF_Extensions)
{
if (Current.Description.Contains(Search_txt.Text))
{
Coll.Add(Current.Description);
}
}
}
Try to use ToLower for both strings before Contains. It should be work.
using (var GC = new GroundCommanderEntities())
{
foreach (var Current in GC.IMF_Extensions.Where(filter => filter.Description.ToLower().Contains(Search_txt.Text.ToLower())))
{
Coll.Add(Current.Description);
}
}
I'm passing a list of guids in a GET request from a JQuery Ajax call.
on my ASP.NET controller side I want to iterate through the list and update the Display_Sort column to match my newly sorted list.
My ID is a Guid and I'm getting a type error in the following code, because it's a string that I'm passing to the Db. However, I can't seem to convert the item(string) into a Guid.
I've tried Guid(item) and it would allow the constructor. Not sure what I'm missing.
Here is the code:
//REORDER HOME ASSETS
public ActionResult ReOrderHome()
{
using (var db = new IFEntities())
{
var myString = Request.QueryString;
var i = 1;
foreach (var item in myString)
{
var myObj = db.HomeContents.Find(item);
myObj.display_order = i;
db.SaveChanges();
i++;
}
}
You can convert item to GUID and then compare like this.
var myObj = db.HomeContents.Find(new Guid(item));
Or, you can use select instead of find. Syntax for select --
foreach (var item in myString)
{
var myObj = db.HomeContents.Select(p => p.<GUID_COLUMN_NAME> == item);
myObj.display_order = i;
db.SaveChanges();
i++;
}
Replace GUID_COLUMN_NAME with actual column name.
I have an 'foreach';
foreach (var item in Model.LstUnidadesGerenciais)
{
var count = Model.LstUnidadesGerenciais.Count;
}
I need to get count with one condition like this:
foreach (var item in Model.LstUnidadesGerenciais)
{
if (item.Level == 1)
{
var count = Model.LstUnidadesGerenciaisWITHCONDITION.Count;
}
}
I think this is simple, but I'm very begginer in C#
Thank you!
Using Linq
var cnt = Model.LstUnidadesGerenciais.Count(x=>x.Level==1);
You can use LINQ Where to select items matching criteria (Level == 1):
var count = Model.LstUnidadesGerenciais.Where(i => i.Level == 1).Count();
Use Count method of LINQ -
var count = Model.LstUnidadesGerenciais.Count(i => i.Level == 1);
In the first example, you don't need the foreach loop. You can tell, because you never use the item, you use the collection instead. I think you need to understand what foreach does here:
foreach (var item in Model.LstUnidadesGerenciais)
{
var count = Model.LstUnidadesGerenciais.Count;
}
foreach will iterate over Model.LstUnidadesGerenciais. This means that for every item in Model.LstUnidadesGerenciais, the code inside the curly brackets is executed, with var item containing the current item of the collection. See MSDN for detailed information
As for the second example: You need a variable that contains a number. In the foreach loop you can increment the variable like:
int count = 0;
foreach (var item in Model.LstUnidadesGerenciais)
{
if (item.Level == 1)
{
count++;
}
}
HI guys i'm trying to load the contents of my file "item.ids" which currently holds this:
1:Stone
2:Grass
3:Dirt
I want to read each line the the file and split it at the ":". I am using the following code:
foreach(String line in File.ReadAllLines("item.ids")) {
items = line.Split(':');
}
foreach (String part in items)
{
addToList(specs, part);
}
}
public void addToArray(Array array, int index, String s)
{
try
{
array.SetValue(s, index);
}
catch (Exception ex)
{
addToList(specs, ex.ToString());
}
}
public void addToList(ListBox listbox, String s)
{
listbox.Items.Add(s);
}
This works but it only does the last line so it will output it like so:
3
dirt
If you could help me along with my code it would be very helpful.
You need to fill the list after every read.
foreach(String line in File.ReadAllLines("item.ids"))
{
items = line.Split(':');
foreach (String part in items)
{
addToList(specs, part);
}
}
... otherwise you're only ever adding the last item by default.
In the 1st loop you set the item field each time you iterate so when you exit the loop it will be set to the last value. You probably want to change to something like this:
foreach(String line in File.ReadAllLines("item.ids"))
{
foreach (String part in line.Split(':'))
{
addToList(specs, part);
}
}
You've closed your loop to early so items will only contain the last iteration
change your code to:
foreach(String line in File.ReadAllLines("item.ids"))
{
items = line.Split(':');
foreach (String part in items)
{
addToList(specs, part);
}
}