Filtering elements of an array - c#

I have an array as
That is, each item has its category in the following index.
I need all the items whose category are TotalNumbers and CurrentNumbers.
I tried
int i = 1;
foreach (string item in statsname)
{
//only number type stats are added to the comboboxes.
if ((statsname[i].ToUpperInvariant()==("TOTALNUMBER")) || ((statsname[i].ToUpperInvariant()==("CURRENTNUMBER"))))
{
comboBox1.Items.Add(statsname[i-1]);
i++;
i++;
}
comboBox1.SelectedIndex = 0;
}
Apparently this does not checks for what I need correctly.
How do I need to modify my codes to get what i need ?

Seems it's better to use a for loop instead of foreach:
for (int i = 1; i < statsname.Length; i += 2)
{
//only number type stats are added to the comboboxes.
if ((statsname[i].ToUpperInvariant()==("TOTALNUMBER")) || ((statsname[i].ToUpperInvariant()==("CURRENTNUMBER"))))
comboBox1.Items.Add(statsname[i-1]);
}

Linq comes to rescue!
var listItems = from s in statsname where s.Equals("TOTALNUMBER", StringComparison.InvariantCultureIgnoreCase) || s.Equals("CURRENTNUMBER", StringComparison.InvariantCultureIgnoreCase) select new ListItem(s);
comboBox1.AddRange(listItems);
Code not tested or compiled, but you can have an idea of what i said.

var filteredValues = Array.FindAll(source, s => s.ToUpperInvariant() == "TOTALNUMBER" ||
s.ToUpperInvariant() == "CURRENTNUMBER").ToList()

I am not sure why you are using index in an foreach loop. The below code should work for you
foreach (string item in statsname)
{
if ( item.ToUpper() == "TOTALNUMBER" || item.ToUpper() == "CURRENTNUMBER")
{
comboBox1.Items.Add(item);
}
}
comboBox1.SelectedIndex = 0;

Related

Get the list of items matching a specific pattern of string

I have a C# model LedgerEntity.
public class LedgerEntity
{
public string AccountNumber{get;set;}
public string Accountlevel{get;set;}
public string AccountName{get;set;}
}
Also I have a list of items of that model class like below
List<LedgerEntity> items=new List<LedgerEntity>();
items=[
{"AccountNumber":"07-01-GRP_10095-81120000","AccountLevel":"Group","AccountName":"JPM"},
{"AccountNumber":"G3-80-GRP_10895-8112SLC0","AccountLevel":"Group","AccountName":"CIT"},
{"AccountNumber":"1C-MULTI-2851170-MULTI_8113xxxx","AccountLevel":"Group","AccountName":"BON"},
{"AccountNumber":"07-MULTI-MULTI_NONCORE-MULTI","AccountLevel":"Group","AccountName":"CUK"}}
]
My requirement is some thing like this.
I need to get all the records which contains
"GRP_*8112(* can have any value like 10095- or 10895- etc...)" in `AccountNumber. Then remove "GRP_" from the record and add "70" in front of the 3rd hyphen.
Example: 07-01-GRP_10095-81120000 --> 07-01-1009570-81120000
also update the Accountlevel of that matched records from Group to Individual.
My expected output is something like this.
matchedItems=[
{"AccountNumber":"07-01-1009570-81120000","AccountLevel":"Individual","AccountName":"JPM"},
{"AccountNumber":"G3-80-1089570-8112SLC0","AccountLevel":"Individual","AccountName":"CIT"},
{"AccountNumber":"1C-MULTI-2851170-MULTI_8113xxxx","AccountLevel":"Group","AccountName":"BON"},
{"AccountNumber":"07-MULTI-MULTI_NONCORE-MULTI","AccountLevel":"Group","AccountName":"CUK"}}
]
Please help me on this.
try this
foreach (var item in items)
{
var grpIndex = item.AccountNumber.IndexOf("GRP_");
if (grpIndex >= 0)
{
var numberIndex = item.AccountNumber.Substring(grpIndex + 4).IndexOf("8112");
if (numberIndex >= 0)
{
item.AccountNumber = item.AccountNumber.Replace("GRP_", "");
item.Accountlevel = "Individual";
var i = 0;
var counter = 0;
foreach (var ch in item.AccountNumber)
{
if (ch == '-') counter++;
if (counter == 3) break;
i++;
}
if (counter == 3) item.AccountNumber = item.AccountNumber.Insert(i, "70");
}
}
}
your problem can be solved with Regex with an expression like this for example:
(10(8|0)95)
You can use following code:
items.Where(item => Regex.IsMatch(item.AccountNumber, #"10(8|0)95)"))

Delete Multiple Items from ObservableCollection

I want to delete multiple items in an ObservableCollection in C#. My code is:
var item = (MoveDataModel)e.SelectedItem;
var answer = await DisplayAlert("Confirmation", "Are you sure you wish to delete " + item.value + "?", "Yes", "No");
if (answer)
{
var type = item.type;
var value = item.value;
foreach (var listItem in items)
{
if ((listItem.value == item.value) || (listItem.location == value && type == "Location"))
{
items.Remove(listItem);
itemCount--;
}
}
}
The first iteration works fine. However, it hangs on
foreach (var listItem in items)
on the second pass. I'm not sure how to make it work.
you can't modify a collection while you're iterating over it. Try something like this (I haven't checked the syntax, may need some cleanup)
var removeList = items.Where(x => x.value == value).Where(y => y.type = type).ToList();
foreach(var i in removeList) {
items.Remove(i);
itemCount--;
}
Have your own counter, cycle backwards through the list so you wont have to readjust for indexes you removed.
System.Collections.ObjectModel.ObservableCollection<object> list = new System.Collections.ObjectModel.ObservableCollection<object>();
private void RemoveStuff()
{
var i = list.Count - 1;
for (; i <= 0; i--)
{
// some checks here to make sure this is the time you really want to remove
list.Remove(i);
}
}

WPF - RadGridView loop through rows. Can't get all rows

I'm trying to iterate through my RadGridView rows, but when I have more than 20 or 30 items, the loop doesn't get all rows.
For example: using this code in a radgridview with 5 items, I can get all of them and do whatever I want, but when my grid has more than 20 items, it gets only 10 rows. Is this a bug or something like that? How can I solve it?
Here's my code:
private List<object> ReturnListFounds(string text)
{
List<object> a = new List<object>();
foreach (var item in myGrid.Items)
{
if (item == null)
continue;
GridViewRow row = myGrid.ItemContainerGenerator.ContainerFromItem(item) as GridViewRow;
if (row == null)
continue;
foreach (GridViewCell cell in row.Cells)
{
if (cell != null && cell.Value != null)
{
string str = cell.Value.ToString();
if (str.Equals(text, StringComparison.InvariantCultureIgnoreCase) || str.ToLower().Contains(text.ToLower()))
{
a.Add(row.Item);
break;
}
}
}
}
return a;
}
#Edit
I found out the problem. The thing is: the method "ItemContainerGenerator.ContainerFromItem(item) as GridViewRow" returns null if the item is outside of the view area. But I'm using this method in a grid containing 123 items and I can only get the row for the 20 first items.
I need to be able to get all of the items, not just the ones in the view area. I have already tried to set the virtualization false (EnableRowVirtualization = false; EnableColumnVirtualization = false;), but it didin't work as well.
Is there a way of getting all of the rows using this method?
Have you tried this?
var rows = StrategyGridView.ChildrenOfType<GridViewRow>();
It works fine for me. Hope it helps!
I tried a lot of things to make this work and I found one. It's not the best way of doing this, but it works. I anyone has anything better, just post here! Share with us!
private List<object> ReturnListFounds(string text)
{
List<object> result = new List<object>();
for (int l = 0; l <= Items.Count; l++)
{
var cell = new GridViewCellInfo(this.Items[l], this.Columns[0], this);
if (cell.Item != null)
{
var props = cell.Item.GetType().GetProperties();
foreach (var p in props)
{
if (p == null || cell.Item == null)
continue;
var t = p.GetValue(cell.Item);
if (t == null)
continue;
var str = t.ToString();
if (str.Equals(text, StringComparison.InvariantCultureIgnoreCase) || str.ToLower().Contains(text))
{
result.Add(cell.Item);
}
}
}
}
result = new List<object>(result.Distinct());
return result;
}

Check if Listbox contains a certain element

I know this question was posted here already multiple times but I've read the threads and nothing works for me so I decided to ask here.
I simply want to check if a certain string is already in my listbox. I've tried the
listBox.Items.Contains("stringToMatch")
but I get nothing.
I also tried
foreach (var item in form1.filterTypeList.Items)
{
if (item.ToString() == "stringToMatch")
{
break;
}
He doesn't find anything. Why? How can I solve that?
Try using this way... FindByText
strig toMatch = "stringToMatch";
ListItem item = ListBox1.Items.FindByText(toMatch);
if (item != null)
{
//found
}
else
{
//not found
}
Please try like below. I am doing for loop on List view items to search string based on item tag or item text.
for (int i = 0; i <= ListView.Items.Count - 1; i++)
{
itmX = ListView.Items.Item(i);
if (itmX.Text.ToString() = "stringToMatch")
{
break;
}
}
OR
for (int i = 0; i <= ListView.Items.Count - 1; i++)
{
itmX = ListView.Items.Item(i);
if (itmX.Tag.ToString() = "stringToMatch")
{
break;
}
}
its so simple now , you simply first find the index of that item in the collection of listbox items and then use this fuction of listbox listBox1.FindStringExact .
private void FindMySpecificString(string searchString)
{
// Ensure we have a proper string to search for.
if (searchString != string.Empty)
{
// Find the item in the list and store the index to the item.
int index = listBox1.FindStringExact(searchString);
// Determine if a valid index is returned. Select the item if it is valid.
if (index != ListBox.NoMatches)
listBox1.SetSelected(index,true);
else
MessageBox.Show("The search string did not find any items in the ListBox that exactly match the specified search string");
}
}
visit the following website for more clarification and examples
https://msdn.microsoft.com/en-us/en-en/library/81wes5yz(v=vs.110).aspx

Removing something from a list

I am trying to remove something from a list using a counter but it is not working for me.
int i =0;
foreach(Rolls rl in rolls)
{
if(rl.getCourseId == courseId && rl.getStudentId == studentId)
{
rolls.RemoveAt(i) ;
}
i++;
}
Can anyone see why this might not work. Its gives me a run time exception:
"Collection was modified; enumeration operation may not execute."
Jonas explained why this won't work, but I thought I'd provide another option.
You can use List<T>.RemoveAll to remove all matching items in one call:
rolls.RemoveAll(rl => rl.getCourseId == courseId && rl.getStudentId == studentId);
You can't modify a collection while you're foreach-ing through it. Try using a regular for loop instead (or a while loop):
int i = 0;
while(i < myCollection.Count)
{
if(removeItem)
myCollection.RemoveAt(i);
else
++i;
}
You can't modify the collection as you iterate through it with foreach.
Try using a for loop like so
for(int i = 0; i < rolls.Length; i++) {
Foreach on a collection won't work like that. Try this:
for (int x = 0; x < rolls.Count; x++)
{
if(rolls[x].getCourseId == courseId && rolls[x].getStudentId == studentId)
{
rolls.RemoveAt(x);
--x; //since we removed an item, the index needs to be updated accordingly
}
}
you should do a loopback
for(int i=rolls.Count-1;i>=0;i--)
if(rolls[i].getCourseId == courseId && rolls[i].getStudentId == studentId)
rolls.RemoveAt(i)

Categories

Resources