part of String contained in a List - c#

Here's what I'm trying to do:
Create a list with some values from mysql.
Search this list with a variable ( I named it Existed )
If Existed contains a specific string, then do some actions.
Here's a sample of my list data:
List ( name users )
Facebook
Google
Yahoo
Strongman
Zombies
Stratovarius
If Existed inside users contains Strong, then perform some action.
My code so far is below. The problem is that it never enters the action and for some reason I believe it does not see "Strong" right.
List<string> users = dbm.FindManagers();
foreach (var Existed in users)
{
if (Existed.Contains(rName_Add_User_result))
{
dbm.AddSubuser(Existed, rName_result);
}
}

Can't reproduce. This works for me:
var rName_Add_User_result = " Strong ";
//List<string> users = dbm.FindManagers();
var users = new List<string>() {"Facebook", "Google", "Yahoo", "Strongman", "Zombies", "Stratovarius"};
foreach (var Existed in users.Where(u => u.ToUpper().Contains(rName_Add_User_result.ToUpper().Trim()))
{
//dbm.AddSubuser(Existed, rName_result);
Console.WriteLine(Existed);
}
Result:
Strongman

Not sure but could be because of case sensitivity. Try converting it to lower and then compare
if (Existed.ToLower().Contains(rName_Add_User_result))
{
dbm.AddSubuser(Existed, rName_result);
}

Related

Add values in list from other API method

I have one list and in that list I am adding values based on class. See below for details.
result.ContactList = contactsResult.Item2.Select(x => new PrjContact() {
Id = x.ID,
UserId = x.UserId,
Name = xName,
Email = x.Email,
}).ToList();
Now I need to call one more API and pass this UserId in that API and get phone number for that user.
Then need to add that phone number in above list in result.ContactList.
I have tried in this way.
foreach (var user in contactsResult.Item2)
{
UserInfo = API.GetUserDetail(user.UserId);
result.ContactList.Select(x => new ProjectContactView()
{
Phone = UserInfo.PhoneNumber
});
}
But this is not working.
This doesn't do anything:
result.ContactList.Select(x => new ProjectContactView()
{
Phone = UserInfo.PhoneNumber
});
Sure, it iterates over result.ContactList and projects it into a new collection. But (1) you don't do anything with that collection and (2) it overwrites every object in that collection with an entirely new object that has only one property set.
For starters, if you want to modify result.ContactList then iterate over that:
foreach (var user in result.ContactList)
{
}
Then if the goal here is to use a property on user to fetch data and update user then just update user:
foreach (var user in result.ContactList)
{
var userInfo = API.GetUserDetail(user.UserId);
user.Phone = userInfo.PhoneNumber
}

botbuilder v 4, dynamic adaptive card with dropdown and capturing values on prompt

I'm using ms botbuilder v 4
I'm using webcontrol, webchat.js, latest, react
Case is pretty trivial:
I want to show list of possible values in dropdown, values will be dynamic (comes from API, i need Titles and Values (Ids) there. Then when user selects some item and clicks OK i want to get value (Id) and work further with that.
As i got it for now only way to show dropdown is using adaptive cards, in v3 there was an option to use adaptive cards in prompts and it also planned for next version: https://github.com/Microsoft/botbuilder-dotnet/issues/1170
But for now only woraround for that is exaplained here:
https://github.com/Microsoft/botbuilder-dotnet/issues/614 , with just list of string everything's working fine, but if i want to store keyvalue pairs (for IDs) i'm not able to do that cos Choices in PromptOptions only accepts list of string (will show below). So only workaround i'm using now is to store whole collection of values and after getting the result go and find it's id. Is there more convinient solution for that?
Here's the code:
var choicesInputs = _teams.Select(s => new AdaptiveChoice { Title = s.Value, Value = s.Value}).ToList();
var card = new AdaptiveCard
{
Version = new AdaptiveSchemaVersion(1, 0),
Body =
{
new AdaptiveTextBlock("Select a team to assign your ticket"),
new AdaptiveChoiceSetInput
{
Choices = choicesInputs,
Id = "setId",
Style = AdaptiveChoiceInputStyle.Compact,
IsMultiSelect = false
}
},
Actions = new List<AdaptiveAction>
{
new AdaptiveSubmitAction
{
Title = "Ok",
Type = "Action.Submit"
}
}
};
signInPhoneState.Teams = _teams;
return await stepcontext.PromptAsync(
"SelectGroupCardDialog",
new PromptOptions
{
Choices = ChoiceFactory.ToChoices(_teams.Select(pair => pair.Value).ToList()),
Prompt = (Activity) MessageFactory.Attachment(new Attachment
{
ContentType = AdaptiveCard.ContentType,
Content = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(card))
})
},
cancellationtoken);
// . . .
var selectedTeamId = signInPhoneState.Teams.FirstOrDefault(pair => pair.Value == sel).Key;
Quick side question (but related in terms i'm using it for workaround):
What is the easiest way to persist some variable though dialog? If i remember correectly In v3 it was as simple as marking a value as public and marking dialog as serializable and that's it, now as i get it you need to create special accessor for each dialog, dublicate property there and manage the state of it, is it correct?
Thanks
You have a dictionary with team ID's as keys and team names as values. You are using the team names as the values for an adaptive choice set that's being used in a prompt, and in the turn after the prompt you're extracting the team ID from the dictionary using the team name. You want a more convenient option.
Option 1: If you're okay with your current setup of keeping the dictionary available
When accessing the data in a dictionary, it is more efficient to access a value using a key than the other way around. That is what dictionaries are for, after all. So instead of using the team names as values in your choice set, you could use team ID's.
var choicesInputs = _teams.Select(s => new AdaptiveChoice { Title = s.Value, Value = s.Key }).ToList();
// . . .
signInPhoneState.Teams.TryGetValue(sel, out string selectedTeamName);
This would mean that if the dictionary is being drawn from some external source that's subject to change, the team name would be as up-to-date as possible.
Option 2: If you don't want to depend on the dictionary for the next turn
You could store both the team ID and the team name in the choice's value.
var choicesInputs = _teams.Select(s => new AdaptiveChoice { Title = s.Value, Value = JsonConvert.SerializeObject(s) }).ToList();
// . . .
var pair = JsonConvert.DeserializeObject<KeyValuePair<string, string>>(sel);
var selectedTeamId = pair.Key;
var selectedTeamName = pair.Value;
This would mean if the underlying data changes between the first turn of the prompt and the second, the choice would still be valid.

Trouble with loops inside list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I has to use a construct like
string json = await SendGraphGetRequest("/users", null);
var jsonObj = JObject.Parse(json);
var values = (JArray)jsonObj["value"];
foreach (var value in values)
List<Users> Users = new List<Models.Users>()
{
foreach (var value in values)
{
};
};
How i have to correct the syntax?
I want to bring values from the json Obj in to the list.
Let's try to break down what you're trying to do into 3 simple steps. First you need to create a List data structure to store your users. Then you'll need to add some users to your empty list. Then finally you can enumerate your list with a for-each loop:
// First create a list of your users.
List<Model.Users> users = new List<Models.Users>();
// Add some users to the list.
users.Add(new Model.Users())
...
...
...
// Now you can loop through the list
foreach (var user in users)
{
// do something with the current user
user.DoSomething();
};
Hope this helps!
You can rewrites it with Linq
List<Users> Users = values.Select(value => new Models.Users( ... )).ToList();
Instead ... or new Models.Users( ... ) you can use your logic
Is each value in values a Users object?
If so,
List<Users> Users = new List<Models.Users>(values);
The List<Users> is initialized with the items in the values collection.
Or, perhaps each value contains some properties that you would use to construct your object:
var Users = new List<Models.Users>();
foreach (var value in values)
{
var newUser = new Users();
//Just making these up.
newUser.Name = value.Name;
newUser.Id = value.UserId;
Users.Add(newUser);
}
var Users = new List<Models.Users>();
foreach (var value in values)
{
var newUser = new Users();
//Just making these up.
newUser.Name = value.Name;
newUser.Id = value.UserId;
Users.Add(newUser);
}
The rest of these examples do the exact same thing - they're just shorthand.
var Users = new List<Models.Users>();
foreach (var value in values)
{
Users.Add(new Users{Name=value.Name, Id=value.UserId});
}
This is using Linq. It does the exact same thing as above. We use it primarily because it looks cool, but the syntax is different until you get used to it.
var Users = new List<Models.Users>(values.Select(
value=>new Users{Name=value.Name, Id=value.UserId}));
It's doing this:
var Users = new List<Models.Users>([some set of Users to initialize the collection]);
and this is the set of users being used to to initialize the collection:
values.Select(value=>new Users{Name=value.Name, Id=value.UserId})
In other words, for each item in values select (create) a new Users object.

How to get query names that references the particular iteration path

With selected project name, I had loaded iteration paths. Now I need to get the query names that references the selected iteration path.
Code to load iteration paths passing project name:
private void LoadIterationPaths(string projectName)
{
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(_tfs.Uri);
var wiStore = tfs.GetService<WorkItemStore>();
var projCollections = wiStore.Projects;
var detailsOfTheSelectedProject = projCollections.Cast<Project>().Where(project => !String.IsNullOrEmpty(_selectedTeamProject.Name))
.FirstOrDefault(project => project.Name.Contains(_selectedTeamProject.Name));
var iterationPathsList = GetIterationPaths(detailsOfTheSelectedProject);
foreach (var iterationPath in iterationPathsList.Where(iterationPath => iterationPath.Contains(projectName)))
{
cmbIterationPath.Items.Add(iterationPath);
}
cmbIterationPath.Enabled = cmbIterationPath.Items.Count > 0;
}
Now, I need to get the list of Query names that references the selected iteration Path. Thanks.
Note: I am able to get all the query names in a project but that i don't need.
For that I used the below code
foreach (StoredQuery qi in detailsOfTheSelectedProject.StoredQueries)
{
cmbQueries.Items.Add(qi.Name);
}
Your code should looks like this
string selectedIterationPath = ...
foreach (StoredQuery qi in detailsOfTheSelectedProject.StoredQueries) {
if (qi.QueryText.Contains(selectedIterationPath) {
cmbQueries.Items.Add(qi.Name);
}
}
This is what me and Beytan Kurt suggested in the comments.
Instead of a dumb Contains, you should use a Regular Expression to account for false positives and negatives.

How do I order a sql datasource of uniqueidentifiers in Linq by an array of uniqueindentifiers

I have a string list(A) of individualProfileId's (GUID) that can be in any order(used for displaying personal profiles in a specific order based on user input) which is stored as a string due to it being part of the cms functionality.
I also have an asp c# Repeater that uses a LinqDataSource to query against the individual table. This repeater needs to use the ordered list(A) to display the results in the order specified.
Which is what i am having problems with. Does anyone have any ideas?
list(A)
'CD44D9F9-DE88-4BBD-B7A2-41F7A9904DAC',
'7FF2D867-DE88-4549-B5C1-D3C321F8DB9B',
'3FC3DE3F-7ADE-44F1-B17D-23E037130907'
Datasource example
IndividualProfileId Name JobTitle EmailAddress IsEmployee
3FC3DE3F-7ADE-44F1-B17D-23E037130907 Joe Blo Director dsd#ad.com 1
CD44D9F9-DE88-4BBD-B7A2-41F7A9904DAC Maxy Dosh The Boss 1
98AB3AFD-4D4E-4BAF-91CE-A778EB29D959 some one a job 322#wewd.ocm 1
7FF2D867-DE88-4549-B5C1-D3C321F8DB9B Max Walsh CEO 1
There is a very simple (single-line) way of doing this, given that you get the employee results from the database first (so resultSetFromDatabase is just example data, you should have some LINQ query here that gets your results).
var a = new[] { "GUID1", "GUID2", "GUID3"};
var resultSetFromDatabase = new[]
{
new { IndividualProfileId = "GUID3", Name = "Joe Blo" },
new { IndividualProfileId = "GUID1", Name = "Maxy Dosh" },
new { IndividualProfileId = "GUID4", Name = "some one" },
new { IndividualProfileId = "GUID2", Name = "Max Walsh" }
};
var sortedResults = a.Join(res, s => s, e => e.IndividualProfileId, (s, e) => e);
It's impossible to have the datasource get the results directly in the right order, unless you're willing to write some dedicated SQL stored procedure. The problem is that you'd have to tell the database the contents of a. Using LINQ this can only be done via Contains. And that doesn't guarantee any order in the result set.
Turn the list(A), which you stated is a string, into an actual list. For example, you could use listAsString.Split(",") and then remove the 's from each element. I’ll assume the finished list is called list.
Query the database to retrieve the rows that you need, for example:
var data = db.Table.Where(row => list.Contains(row.IndividualProfileId));
From the data returned, create a dictionary keyed by the IndividualProfileId, for example:
var dic = data.ToDictionary(e => e.IndividualProfileId);
Iterate through the list and retrieve the dictionary entry for each item:
var results = list.Select(item => dic[item]).ToList();
Now results will have the records in the same order that the IDs were in list.

Categories