Updating List<string> values using linq C# - c#

I have a list of strings that I would like to iterate through and change the values if certain items in the list if they match up to a string value in a separate list of objects.
User inputs an email address into an Event object that contains a list of EventMembers:
List<string> EventMembers
I would then like to check through all users in the database to find the username(e-mail address) that matches with the inputted e-mail address
i understand I cannot change values in a list using a foreach loop, but i'm lost with what to do with linq. Basically i'm trying to do something like this:
var allUsers = _userManager.Users
foreach (var a in allUsers)
{
foreach (var e in #event.EventMembers)
{
if (e == a.UserName)
{
e = a.FirstName + a.LastName;
}
}
}

The best thing would be to define an initial collection of members so you don't keep modifying the list while the foreach is still running. You could then check if EventMembers contain the username and then replace it by accessing the value with the index.
var allUsers = _userManager.Users;
List<string> Members;
foreach (var a in allUsers)
{
if (#event.EventMembers.Contains(a.UserName))
{
var index = #event.Members.IndexOf(a.UserName);
Members[index] = a.FirstName + a.LastName;
}
}
EventMembers = Members;

Related

How to combine two columns from a database with LINQ?

// Appetizers Filter
var Appetizers =
from a in this.restaurantMenuDataSet.Menu
where a.Category == "Appetizer"
select a;
foreach (var a in Appetizers) AppCombo.Items.Add(a.ItemName);
So with this I get appetizers from an access database, but I also want to display its price along side it in ComboList. So basically I want the list to show "Nachos $5.95"
Database:
ComboList:
You can use String.Format to combine ItemName and Price in order to display in combobox:
foreach (var a in Appetizers)
{
var displayName = String.Format("{0} {1}", a.ItemName,a.Price);
AppCombo.Items.Add(displayName);
}

Specified Cast Not Valid - XamarinFirebase

This is my firebase database structure
Database Structure
In the child, there are values , Name, Country, Age and Uid. The Uid is the focus in my question.
I am try to fetch the children of the node (Chat) based on the current logged in user.
I am basically trying to do a comparison here that, firebase should get me children who only have the Uid = user.uid. i.e the current logged in user. I thought Equals() could do the trick but i get an error with the cast.
The error points at this line var items = snapshot.Children?.ToEnumerable<DataSnapshot>().Equals(user.uid).ToString;
public void OnDataChange(DataSnapshot snapshot)
{
var items = snapshot.Children?.ToEnumerable<DataSnapshot>().Equals(user.uid).ToString;
var key = snapshot.Key;
HashMap map;
foreach (DataSnapshot item in items)
{
}
Console
my snapshot test: DataSnapshot { key = Chat, value = {-KomfGbZxCGESgyo1PFT={Name=Testing , Ref=7YB3mxMRXxW4lzhbhxi1bx7K4Pf1,
}, -KomcJyR5dCxFucJSB0I={Name=Hi, Ref=K6TEpccn1TbB32T8ThFsYnIl6Wm2, }} }
If you want to filter the user based on Ref attribute, I suggest you make an if-statement inside foreach loop to filter the item:
public void OnDataChange(DataSnapshot snapshot)
{
var items = snapshot.Children?.ToEnumerable<DataSnapshot>();
HashMap map;
foreach (DataSnapshot item in items)
{
//filter the user first
map = (HashMap)item.Value;
string userId = map.Get("Ref")?.ToString();
if (userId!=null&& userId == user.uid)
{
//do what you want to do here.
}
}
When you use ToEnumerable, the type of returned objects is DataSnapshot and it cannot be compared to user.uid. You might want to use linq to grab what you wants. something like:
var items = snapshot.Children?.ToEnumerable(x=> x.uid == user.uid)

Can't check whether a list contains a select item in C#

I am storing a list of select items in my view model. When adding the correct select items i get them from a list stored in a spreadsheet, some of which are duplicates. I want to eliminate these duplicates and have the following code to do so.
//Fill with all the install locations
foreach (App y in applications)
{
//Check if the app has a server listed
if (y.Server != "")
{
SelectListItem ItemToAdd = new SelectListItem { Text = y.Server, Value = y.Server };
//Check if the the item has already been added to the list
if (!vm_modal.serverLocations.Contains(ItemToAdd))
{
vm_modal.serverLocations.Add(ItemToAdd);
}
}
}
However this is not working as it is just adding everything so there are a lot of duplicates. I don't know if contains works differently because I'm not just dealing with regular strings or something like that.
In this instance, as you are using the same string for Text and Value, you can iterate through your source, and add non-duplicate values to a simple List<string> before adding all of the checked values to your select list.
List<string> result = new List<string>();
foreach (App y in applications)
{
//Check if the app has a server listed and for duplicates
if (y.Server != "" && !result.Contains(y.Server))
{
result.Add(y.Server);
}
}
result.ForEach(x => vm_modal.serverLocations.Add(
new SelectListItem(){Text = x, Value = x}));
for a "one liner" of what ste-fu presented you can write
vm_modal.serverLocations
.AddRange(applications
.Where(app => app.Server != "")
.Select(app => app.Server)
.Distinct()
.Select(server => new SelectListItem{ Text = server, Value = server }));

Removing an element from list if it contains particular text in it

I have a C# method in which I look for certain text say username in a list with element in the format username + datetime and if any part of text matches the element in the list, then the entire element has to be removed from the list
Method to add to the c# List
string active_user = model.UserName.ToString();
string datetime = "(" + DateTime.Now + ")";
List<string> activeUsers = new List<string>();
if (activeUsers.Any(str => str.Contains(active_user)))
{
//do nothing
}
else
{
activeUsers.Add(active_user+datetime);
}
Now I would like a method that deletes the element if it matches the username or any part of element something like
if (activeUsers.Contains(active_user))
{
activeUsers.Remove(active_user);
}
While the other answers are correct, you should note that they will delete any matches. For example, active_user = "John" will remove "John", "John123", "OtherJohn", etc.
You can use regular expressions to test, or if user names don't have parentheses, do your test like this:
string comp = active_user + "("; // The ( is the start of the date part
activeUsers.RemoveAll(u => u.StartsWith(comp));
Also note, this is case sensitive.
You can do something like
activeUsers.RemoveAll(u => u.Contains(active_user));
That will match and remove all elements of activeUser that contain the text in active_user.
var user = activeUsers.FirstOrDefault(au => au.Contains(active_user);
if(user != null)
activeUsers.Remove(user);
if you are only wanting to remove the first match, else :
var users = activeUsers.Where(au => au.Contains(active_user);
foreach(var user in users)
activeUsers.Remove(user);
Or more simply, the RemoveAll method Eric answered with.
If i Want to remove Numeric String Values List Items from my List
List<ModelName> ModelList = new List<ModelName>();
var regex = new Regex(#"\d");
foreach(var item in ModelList.ToList())
{
if (regex.IsMatch(item.PropertyName))
{
ModelList.RemoveAll(t => t.PropertyName== item.PropertyName);//Or
ModelList.RemoveAll(t => t.PropertyName.Contains(item.PropertyName));//Or You Can Use Contains Method
}
}
return ModelList;
This will remove all items from list those having Numeric values as a string and return only Character String in List items

preventing duplicates when inserting nodes to treeview control

I want to create a hierarchical view of strings based on first two characters.
If the strings are:
AAAA,AAAA,BBDD,AABB,AACC,BBDD,BBEE
I want to reate a treeview that looks like this:
AA
AAAA
AABB
AACC
BB
BBDD
BBEE
I currently have some code that looks like this (inside a loop over the strings):
TreeNode pfxNode;
if (treeView1.Nodes[pfx]!=null) {
pfxNode = treeView1.Nodes[pfx];
}
else {
pfxNode = treeView1.Nodes.Add(pfx);
}
if (!pfxNode.Nodes.ContainsKey(string)) {
pfxNode.Nodes.Add(string, string + " some info");
}
For some reason this ends up with multiple "AA" nodes at the top level.
What am I missing?
please no pre-filtering of strings I want to be able to check if a specific treenode exists based on its key.
thanks
else {
pfxNode = treeView1.Nodes.Add(pfx);
}
There's your mistake, you are forgetting to set the key of the tree node. So the next ContainsKey() won't find it. Fix:
pfxNode = treeView1.Nodes.Add(pfx, pfx);
Use this:
var q = from s in arr
group s by s.Substring(0, 2) into g
select new
{
Parent = g.Key,
Children = g.Select (x => x).Distinct()
};
foreach (var item in q)
{
var p = new TreeNode(item.Parent);
TreeView1.Nodes.Add(p);
foreach (var item2 in item.Children)
p.Nodes.Add(new TreeNode(item2));
}

Categories