C# List Split and Join Specific Length - c#

I pull object in MSSQL and i would like to try below
List for example
Num1 = 123123
Num2 = 2222
Num3 = 3456734567
Num4 = 4669321469321
How do i combine this list since the length is not the same?
Expected Result :
CombinedNum = 123223456746693211232234567469321
Code i tryed :
List<string> first4List = new List<string>();
List<string> Num_1List = new List<string>();
List<string> Num_2List = new List<string>();
List<string> Num_3List = new List<string>();
List<string> Num_4List = new List<string>();
while (render.Read())
{
first4List.Add(render["N1"].ToString());
last4List.Add(render["N2"].ToString());
HashList.Add(render["N3"].ToString());
FlagList.Add(render["N4"].ToString());
ReasonList.Add(render["N5"].ToString());
render.Close();

If what you are trying to achieve is to generate a string that is a combination of all elements in a list then try the below.
var Num_1List = new List<string>
{
"123123", "2222", "3456734567", "4669321469321"
};
var combinedString = Num_1List.Aggregate((current, part) => current + part);

Related

String Arrays in c#. Removing elements from one string array which are their in another string array

I have two string arrays -
string[] One = new string[3];
One[0] = "Pen";
One[1] = "Pencil";
One[2] = "card";
and,
string[] Two = new string[2];
Two[0] = "card";
Two[1] = "drive";
Now, I want a new string array from these two, such that the final result does not contain any element of the Two array. i.e. it should have, "Pen", "Pencil" only.
This simple linq query can give you result.
var res = One.Except(Two);
Further, if in case you need to ignore case, use overload version of above method as:
var res = One.Except(Two, StringComparer.OrdinalIgnoreCase);
OR, Equivalently.
var res = One.Where(x=>!Two.Contains(x)).ToArray();
You can use Linq -
var res = One.Where(x => Two.Find(x) == null);
Or even better:
string[] One = new string[3];
One[0] = "Pen";
One[1] = "Pencil";
One[2] = "card";
string[] Two = new string[2];
Two[0] = "card";
Two[1] = "drive";
var res = One.Except(Two);
You need something like non-intersect
string[] One = new string[3];
One[0] = "Pen";
One[1] = "Pencil";
One[2] = "card";
string[] Two = new string[2];
Two[0] = "card";
Two[1] = "drive";
var nonintersectOne = One.Except(Two);
foreach(var str in nonintersectOne)
Console.WriteLine(str);
// Or if you want the non intersect from both
var nonintersectBoth = One.Except(Two).Union(Two.Except(One)).ToArray();
foreach(var str in nonintersect)
Console.WriteLine(str);
Output 1:
Pen
Pencil
Output 2:
Pen
Pencil
drive

Add quotes to list elements

How do I append each element in usersList and add quotes to each User like so, "User1","User2","User3"
class Program {
public static List<string> usersList = new List<string>();
static void Main(string[] args)
{
userList = ["User1,User2,User3"]
}
}
Requires Linq:
using System.Linq;
I'm not certain this is what you're looking for, but given a List of users like so:
List<string> usersList = new List<string> { "User1", "User2", "User3" };
You can create a new list of quoted users like so:
List<string> quotedList = usersList.Select(u => $"\"{u}\"").ToList();
And output them as a comma-delimited list:
Console.WriteLine(string.Join(", ", quotedList.ToArray()));
List<String> userList = new List<String>();
String userData = "User1,User2,User3";
userList.AddRange(userData.Split(',').Select(x => String.Format("\"{0}\"", x)));
// check area
for(int i = 0; i < userList.Count; i++)
{
Console.WriteLine(userList[i]);
}

foreach and index in .ToDictionary C#

I am web-scraping some data and trying to write the scraped data to a json file using C# newtonsoft.Json
I get stuck when writing a foreach in my .ToDictionary function as well as not being able to ++ an index into my .ToDictionary function.
My class:
public class JsonParametersData
{
public bool required { get; set; }
public bool list { get; set; }
public List<string> options { get; set; }
}
My arrays
var jsonData = new List<Dictionary<string, Dictionary<string, JsonParametersData>>>();
var moduleParameters = new List<string>();
var parameterOptionsArray = new List<List<string>>();
var parameterOptions = new List<string>();
var requiredArray = new List<bool>();
var listArray = new List<bool>();
string moduleName = item.Attributes["href"].Value.Replace("_module.html", "");
The code which is commented shows what I am trying to do.
int index = 0;
jsonData.Add(new Dictionary<string, Dictionary<string, JsonParametersData>>()
{
{
moduleName,
moduleParameters
.ToDictionary(n => n,
n => new JsonParametersData
{
required = requiredArray[index],
list = listArray[index],
options = new List<string>() { "option1", "option2" },
/*
foreach (var parameteroption in parameterOptionsArray[index])
{
options.Add(parameteroption);
}
index++;
*/
})
}
});
string json = JsonConvert.SerializeObject(jsonData.ToArray());
//write string to file
System.IO.File.WriteAllText(#"path", json);
Your parameterOptionsArray is not an Array, but a List of lists.
The thing is that parameterOptionsArray[index] is a List, not a string. So you should use AddRange() instead of Add().
parameterOptionsArray.Foreach(parameteroption => options.AddRange(parameteroption));
As I´ve written in the comments you can make only assignments in an object-initializer. Thus the following is allowed:
var a = new { MyMember = anInstance }
whilst this is not:
var a = new { MyMember = anInstance, anInstance.DoSomething() };
That´s one of those cases where you should not use Linq at all, as it leads to more confusion than it helps. Instead use a good old-styled loop:
int index = 0;
var innerDict = new Dictionary<string, JsonParametersData>();
foreach(var name in moduleParameters)
{
innerDict[name] = new JsonParametersData
{
required = requiredArray[index],
list = listArray[index],
options = new List<string>() { "option1", "option2" },
}
innerDict[name].Options.AddRange(parameterOptionsArray[index]);
index++;
}
var dict = new Dictionary<string, Dictionary<string, JsonParametersData>>();
dict[moduleName] = innerDict;
jsonData.Add(dict);
string json = JsonConvert.SerializeObject(jsonData.ToArray());
You appear to have a jagged array in parameterOptionsArray. You can make use of SelectMany here. Perhaps following sample can help:
string[][] parameterOptionsArray = new string[2][];
parameterOptionsArray[0] = new string[2];
parameterOptionsArray[0][0] = "1";
parameterOptionsArray[0][1] = "2";
parameterOptionsArray[1] = new string[2];
parameterOptionsArray[1][0] = "3";
parameterOptionsArray[1][1] = "4";
var testing = new {options = parameterOptionsArray.SelectMany(x => x).ToList()};
testing.options.ForEach(x => Console.WriteLine(x));

How to get a specific field of list of objects in an array of strings

I have a list of persons like this :
foreach (GridViewRow r in gv_contactList.Rows)
{
Person p = new Person();
p.Id = int.Parse(gv_contactList.DataKeys[r.RowIndex].Value.ToString());
p.Name = r.Cells[1].Text.TrimEnd();
p.Mobile = r.Cells[2].Text.TrimEnd();
p.Email = r.Cells[3].Text.TrimEnd();
p.Pkind = 1;//ToDo
plst.Add(p);
}
How to get an array of mobile numbers in string[]
in the same previous loop where the mobile number is not null or empty .
instead of looping again through the list of persons to put the mobile numbers in the array.
Not really sure what you want. But if you want an array of string phone numbers from your Person List plst you can do:
string[] phoneArray = plist
.Where(r=>string.IsNullOrWhiteSpace(r.Mobile))
.Select(r=>r.Mobile.ToString())
.ToArray();
var mobiles = new List<string>();
foreach (GridViewRow r in gv_contactList.Rows)
{
...
p.Mobile = r.Cells[2].Text.TrimEnd();
if (!String.IsNullOrEmpty(p.Mobile)) {
mobiles.Add(p.Mobile);
}
...
}
var mobilesArray = mobiles.ToArray();
Declare an ArrayList before foreach:
ArrayList<String> mobNums = new ArrayList<String>();
within foreach add the mobile no. to it:
mobNums.Add(p.Mobile);
After foreach change it to Array:
String[] arr = mobNums.ToArray();
Assuming plst is already existing:
var plst = ...
var persons = from GridViewRow r in gv_contactList.Rows
select new Person {
Id = int.Parse(gv_contactList.DataKeys[r.RowIndex].Value.ToString()),
Name = r.Cells[1].Text.TrimEnd(),
Mobile = r.Cells[2].Text.TrimEnd(),
Email = r.Cells[3].Text.TrimEnd(),
Pkind = 1,
};
var mobiles = persons.Aggregate(new List<string>(), (acc, cur) =>
{
plst.Add(cur);
if (!string.IsNullOrEmpty(cur.Mobile))
acc.Add(cur.Mobile);
return acc;
}).ToArray();
The enumeration happens just once.

cant add string to list of string c#

I'm reading a local csv file which has data and I will eventually use to load into a database. My question is simple in nature but I can't seem to grasp the concept. Below is my code. Pretty simple stuff.
static void loadTables() {
int size = new int();
string[] empid = new string[0];
//string[] empid = new string();
List<string[]> EmployeeName = new List<string[]>();
List<string[]> EmployeeId = new List<string[]>();
List<string[]> Group = new List<string[]>();
List<string[]> Org = new List<string[]>();
List<string[]> Fund = new List<string[]>();
try {
using (StreamReader readFile = new StreamReader("C:\\temp\\groupFundOrgReport.csv"))
{
string line;
string[] row;
size = 0;
while ((line = readFile.ReadLine()) != null)
{
row = line.Split(',');
/*resize the array up by 1*/
Array.Resize(ref empid,empid.Length+1);
/*I'm using size as a counter to add to the slot on the array.*/
empid[size] = row[0].Remove(0,1);
// here I receive error (the best overload match of system generic list?...etc)
EmployeeName.Add(row[0]);
size++;
}
}
}
catch(Exception e){
Console.WriteLine(e);
}
}
I have a list of string but any attempts to add a string to it gets me an error. In other words if I try to do this EmployeeName.Add(row[0].ToString); I get an error. However if I comment the line out I can use an old fashion array. I really like to use a list but I can't seem to be able to pass the value that I want. Can someone please point me in the right direction?
I guess from your code that the employee name is the first field of the CSV file.
You have declared EmployeeName as a List of arrays of strings List<string[]>, not as a list of strings List<string>.
Row[0] is the first string in an array, so you are trying to add a string to a list that is expecting you to add an array of strings.
You should just declare EmployeeName as a List<string>, using a line like:
List<string> EmployeeName = new List<string>();
or
var EmployeeName = new List<string>();
Your problem is the declaration of EmployeeName, it is a List of string arrays:
List<string[]> EmployeeName = new List<string[]>();
Change it to:
var EmployeeName = new List<string>();
Or, use the List<string[]> accordingly ...
EmployeeName is a List<string[]> so you have to write:
EmployeeName.Add(row);
To remove empty entries while splitting a string use:
row=line.Split(New String() {","},
StringSplitOptions.RemoveEmptyEntries);
All of them are List's of String Array's
List<string[]> EmployeeName = new List<string[]>();
List<string[]> EmployeeId = new List<string[]>();
List<string[]> Group = new List<string[]>();
List<string[]> Org = new List<string[]>();
List<string[]> Fund = new List<string[]>();
Only variable you can add would be like
//Define array of strings
var strArr = new string[] {"abc", "xyz"};
then you can call
EmployeeName.Add(strArr);
although changing the List generic type to string type will solve your problem
List<string> EmployeeName = new List<string>();
List<string> EmployeeId = new List<string>();
List<string> Group = new List<string>();
List<string> Org = new List<string>();
List<string> Fund = new List<string>();
var str = "My String";
EmployeeName.Add(str);

Categories

Resources