Create String of Comma Separated Quotes from List - c#

I have a class called user that contains a list of groups that are strings ( Group A, Group B, Group C)
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public User()
{
Groups = new List<string>();
}
}
I am then using a json deserializer to create the list of users and groups. However I would like to be able to get a string of the groups with this format for each user:
"Group A", "Group B", "Group C"
I have tried this:
string[] AllGroups;
AllGroups = (string[])usrList[0].Groups.ToArray();
return string.Join(",", AllGroups);
However it is giving me a list in this format (with no quotes):
Group A, Group B, Group C
Any idea what I am doing wrong here?

Any idea what I am doing wrong here?
Well you're not adding the quotes anywhere - so you're not getting them.
You can surround each item with quotes yourself easily enough:
return string.Join(", ", usrList[0].Groups.Select(x => "\"" + x + "\""));
That's assuming you're using .NET 4 or higher - if you're using .NET 3.5 (which doesn't have quite as good string.Join support) you need to create an array, but you don't need to cast it to string[] (as ToArray already returns an array)...
return string.Join(", ", usrList[0].Groups
.Select(x => "\"" + x + "\"")
.ToArray());
I've added a space after the comma delimiter as well, given your question - I suspect your current code is really giving you Group A,Group B,Group C.

Assuming you want to get "" as a result when there are no values, you can do this:
return "\"" + string.Join("\", \"", AllGroups) + "\"";
Note that this is not an empty string - it's a string which contains two quotes.
If you want to return null or the empty string using this code, you'd need to check the size of AllGroups first.
var AllGroups = usrList[0].Groups;
if (AllGroups.Count() == 0) return null;
else return "\"" + string.Join("\", \"", AllGroups) + "\"";

Related

Check if a particular string is contained in a list of strings

I'm trying to search a string to see if it contains any strings from a list,
var s = driver.FindElement(By.Id("list"));
var innerHtml = s.GetAttribute("innerHTML");
innerHtml is the string I want to search for a list of strings provided by me, example
var list = new List<string> { "One", "Two", "Three" };
so if say innerHtml contains "One" output Match: One
You can do this in the following way:
int result = list.IndexOf(innerHTML);
It will return the index of the item with which there is a match, else if not found it would return -1.
If you want a string output, as mentioned in the question, you may do something like:
if (result != -1)
Console.WriteLine(list[result] + " matched.");
else
Console.WriteLine("No match found");
Another simple way to do this is:
string matchedElement = list.Find(x => x.Equals(innerHTML));
This would return the matched element if there is a match, otherwise it would return a null.
See docs for more details.
You can do it with LINQ by applying Contains to innerHtml for each of the items on the list:
var matches = list.Where(item => innerHtml.Contains(item)).ToList();
Variable matches would contain a subset of strings from the list which are matched inside innerHtml.
Note: This approach does not match at word boundaries, which means that you would find a match of "One" when innerHtml contains "Onerous".
foreach(var str in list)
{
if (innerHtml.Contains(str))
{
// match found, do your stuff.
}
}
String.Contains documentation
For those who want to serach Arrray of chars in another list of strings
List WildCard = new() { "", "%", "?" };
List PlateNo = new() { "13eer", "rt4444", "45566" };
if (WildCard.Any(x => PlateNo.Any(y => y.Contains(x))))
Console.WriteLine("Plate has wildchar}");

Problems with List<string> when adding strings by variable

I wanna do a list without duplicates from a file which have too many lines with identifier, sometimes repeated. When I try using List<string>.Contains, it doesn't work. This is, I think, because I'm adding object instead of strings directly.
public List<string> obterRelacaoDeBlocos()
{
List<string> listaDeBlocos = new List<string>();
foreach(string linhas in arquivos.obterLinhasDoArquivo())
{
string[] linhaQuebrada = linhas.Split('|');
string bloco = linhaQuebrada[1].ToString();
if (listaDeBlocos.Contains((string)bloco) != true)
{
listaDeBlocos.Add( bloco + ":" + listaDeBlocos.Contains(bloco).ToString());
}
}
return listaDeBlocos;
}
You're appending ":" + listaDeBlocos.Contains(bloco).ToString() to the string before you add it to the list. That's not going to match when you encounter the same word again, so Contains will return false and the same word will get added again.
I don't see what point it serves to append ": true" to the end of each string in the list anyway, so just remove that part and it should work.
if (!listaDeBlocos.Contains(bloco))
{
listaDeBlocos.Add(bloco);
}
Since you're only interested in one part of each string, based on how you're splitting, you could rewrite your method using LINQ. This is untested but should work:
public List<string> obterRelacaoDeBlocos()
{
return arquivos.obterLinhasDoArquivo().Select(x => x.Split('|')[1]).Distinct().ToList();
}

Write to file List element of struct

I have such struct:
public struct ParsedUser
{
public string Username;
public string pk;
public string RandPhotoId;
}
And I have filled List of ParsedUser:
List<ParsedUser> users;
How to write to file only Usernames?
Something like File.AppendAllLines(tag + ".txt", users.Select(x => new { x.Username} ));
You were close:
File.AppendAllLines(tag + ".txt", string.Join("\r\n", users.Select(u => u.Username)));
First of all you don't need to create a new object, you want just the name, so select it plainly.
Second, ju need to join these strings with "\r\n", a newline plus carriage return, that is what the string.Join does.
You can simply use :
var userNames = users.Select(x => x.Username).ToArray();
File.AppendAllLines(tag + ".txt", userNames);
Method AppendAllLines create new line per every string in IEnumerable<string>.

Perform a linq expression for 'contains' with searching through a list for 'like' not exact matches

Okay so I am stumped and have looked around for this and I know I am doing the implementation of something very simple more complex than it needs to be. Basically I have a POCO object that will have a member that contains a string of other members. This is labeled as 'st' and it may have strings that are comma seperated series in one string. Thus I may have two members of strings be 'images, reports' and another 'cms, crm'. I have a list of objects that I want to match for PART OF those strings but not necessarily all as a DISTINCT LIST. So a member of 'cms' would return the value of anything that contained 'cms' thus 'cms, crm' would be returned.
I want to hook this up so a generic List can be queried but I cannot get it to work and was looking at other threads but there methods do not work in my case. I keep thinking it is something simple but I am missing it completely. Please let me know if anyone has better ideas. I was looking here but could not get the logic to apply correctly:
Linq query list contains a list
I keep trying methods of 'Select', 'SelectMany', 'Contains', 'Any', 'All' at different levels of scope of the continuations to no avail. Here is a simple excerpt of where I am at with a simple Console app example:
public class Program
{
public class StringModel
{
public string name { get; set; }
public string str { get; set; }
}
static void Main(string[] args)
{
string s = "";
List<StringModel> sm = new List<StringModel>
{
new StringModel
{
name = "Set1",
str = "images, reports"
},
new StringModel
{
name = "Set2",
str = "cms, crm"
},
new StringModel
{
name = "Set3",
str = "holiday, pto, cms"
}
};
sm.ForEach(x => s += x.name + "\t" + x.str + "\n");
var selected = new List<object> {"cms", "crm"};
s += "\n\nITEMS TO SELECT: \n\n";
selected.ForEach(x => s += x + "\n");
s += "\n\nSELECTED ITEMS: \n\n";
// works on a single item just fine
var result = sm.Where(p => p.str.Contains("cms")).Select(x => new { x.name, x.str}).ToList();
// I am not using select to get POCO on other methods till I can get base logic to work.
// Does not return anything
var result2 = sm.Where(p => selected.Any(x => x == p.str)).ToList();
// Does not return anything
var result3 = sm.Where(p => selected.Any(x => selected.Contains(p.str))).ToList();
result.ForEach(y => s += y + "\n");
s += "\n\n2nd SET SELECTED: \n\n";
result2.ForEach(y => s += y + "\n");
s += "\n\n3rd SET SELECTED: \n\n";
result3.ForEach(y => s += y + "\n");
Console.WriteLine(s);
Console.ReadLine();
}
}
result2 is empty because you're comparing an object (x) with a string (StringModel.str). This will be a reference comparison. Even if you convert x to a string, you'll be comparing each value in selected ("cms", "crm") with your comma-separated string values ("images, reports", "cms, crm", "holiday, pto, cms").
result3 is empty because selected ("cms", "crm") does not contain any of the string values ("images, reports", "cms, crm", "holiday, pto, cms"), although in this case at least the comparisons are value comparisons.
I think you're looking for something like:
var result = sm.Where(p => selected.Any(x => p.str.Contains((string)x)));

how to get words inside a string

well i am working with xml but it is not important now, the problem is the next
it returns me something so
<xml>blalbalblal asfjñs
fasdf
iduser=dmengelblack; name=angel; lastname=uc;
blablal
iduser=cccarlos; name=carlos; lastname=uc;
how do i get (dmengelblack, angel, uc, carlos, uc)
i want to save every row...
remember all it is inside a string how do i get "dmengelblack", "angel", "uc" save it, everyone in a variable, and save all this in a variable too.. for example
string id="dmengelblack";
string name="angel";
string lastname="uc";
all="dmengelblack angel uc"
and i need to save the other row too, and all rows it can have
what do i know?
i know before than username it is "id="
i know before name it is "name="
i know before lastname it is "lastname="
i kwnow everyone finish with ";"
Simple way in java is to read the file as a stream, iterate through that and get the substring between
iduser= and ;
and
name= and ;
and
lastname= and ;
EDIT: With this code you will get the list of all the filed you want as
OUTPUT:
[iduser=dmengelblack, iduser=cccarlos]
[name=angel, name=carlos]
[lastname=uc, lastname=uc]
So now you interate through these list, split the each entry on =, you will the value you wanted at the second index on split.
CODE:
String str = "<xml>blalbalblal asfjñs" + "fasdf"
+ "iduser=dmengelblack; name=angel; lastname=uc;"
+ "blablal"
+ "iduser=cccarlos; name=carlos; lastname=uc;";
List<String> iduser = new ArrayList<String>();
List<String> name = new ArrayList<String>();
List<String> lastname = new ArrayList<String>();
int i = 1;
while(str.indexOf("iduser=", i) > 0) {
i=str.indexOf("iduser=",i);
iduser.add(str.substring(i, str.indexOf(";", i)));
name.add(str.substring(str.indexOf("name=", i), str.indexOf(";", str.indexOf("name=", i))));
lastname.add(str.substring(str.indexOf("lastname=", i), str.indexOf(";", str.indexOf("lastname=", i))));
i=str.indexOf("lastname=",i);
}
System.out.println(iduser);
System.out.println(name);
System.out.println(lastname);
hope this helps.
I would use RegEx to extract the pattern of key values into a hast table (dictionary), then use a know key mapping to assign it to the variables you have (iteration with a switch statement or something)
In c# (and other languages, but they will have different syntax) you can split a string into an array of strings like this:
string myString = "item1;item2;item3";
string[] separateStrings = myString.Split(';');
This will give you a string array like:
string[0] = "item1";
string[1] = "item2";
string[2] = "item3";
I would also suggest you clean up you tags to only tag what you really care about.

Categories