How to add a instance of class into a variable c#? - c#

How to add a instance of class into a variable c#?
for (int i = 0; i < 8; i++)
{
var msg = new Param
{
type = "text",
text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
};
// What I need to do to acumulate msg variable into a new variable?
}

Append the object to a list that exists outside of the loop, instead of just to a variable that only exists inside the loop. For example:
var msgs = new List<Param>();
for (int i = 0; i < 8; i++)
{
msgs.Add(new Param
{
type = "text",
text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
});
}
// here you have the list of Param objects created in your loop

You can create a list of Param
var listParam = new List<Param>();
for (int i = 0; i < 8; i++)
{
var msg = new Param
{
type = "text",
text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
};
listParam.Add(msg);
}

const int count = 8;
var messages = new Param[count];
for (int i = 0; i < count; i++)
{
var msg = new Param
{
type = "text",
text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
};
messages[i] = msg;
}

Related

How to turn values in variables into array indexes

Hoping I can explain this clearly ... I have a collection of variables:
static string sRunnerSetName, sFH, sR1, sH2, sR2, sH3, sR3, sH4, sR4, sH5, sR5 = "";
static int iRunnerSetName, iFH, iR1, iH2, iR2, iH3, iR3, iH4, iR4, iH5, iR5 = 0;
Each of the int variables hold a unique value, which provide the order that the corresponding string variables need to be combined and put into a concatenated string. So iFH holds the sorting/order-number position for where the string sFH will be positioned in the concatenated string.
I'm just stuck with how to use the values in each int to create the order of strings?
As an example -
iFH = 2; i1R = 0; i2R = 1;
sFH = "z"; s1R = "x"; s2R = "y";
Looking to use the values in the integer variables to create the order/position of each string so that the concatenated result of the above would be "xyz".
Create a class holding a string and an int:
class Item
{
public string Description {get;set;}
public int SortOrder {get;set;}
}
Create a list (or another collection, which fits better to your needs) of these items:
List<Item> list = new List<Item>
{
new Item { Description = "Test", SortOrder = 4 },
new Item { Description = "Test2", SortOrder = 3 },
new Item { Description = "sadf", SortOrder = 1 },
new Item { Description = "Example", SortOrder = 2 },
new Item { Description = "something", SortOrder = 5 }
};
You can use LINQ to sort your list:
list = list.OrderBy(x => x.SortOrder).ToList();
You can then output it on console:
Console.WriteLine(string.Join("\n", list.Select(x => x.Description)));
Try it online
You could use arrays here; copy the data into the arrays, then sort them using the index one as the master:
string a = "a", b = "b", c = "c", d = "d";
int ia = 3, ib = 2, ic = 0, id = 1;
string[] sarr = null;
int[] iarr = null;
try
{
// put the data into vectors; we can't talk about variables
// abstractly, but we *can* talk about vectors by position
sarr = ArrayPool<string>.Shared.Rent(4);
iarr = ArrayPool<int>.Shared.Rent(4);
sarr[0] = a;
sarr[1] = b;
sarr[2] = c;
sarr[3] = d;
iarr[0] = ia;
iarr[1] = ib;
iarr[2] = ic;
iarr[3] = id;
var sb = new StringBuilder();
Array.Sort(iarr, sarr, 0, 4);
for (int i = 0; i < 4; i++)
{
sb.Append(sarr[i]);
}
sb.AppendLine();
Console.WriteLine(sb.ToString());
}
finally
{
if (sarr is not null) ArrayPool<string>.Shared.Return(sarr);
if (iarr is not null) ArrayPool<int>.Shared.Return(iarr);
}
Not super efficient, but it would work. However, it is probably better to re-frame the problem; from your example:
iFH = 2; i1R = 0; i2R = 1;
sFH = "z"; s1R = "x"; s2R = "y";
If we instead say:
string[] sarr = { "z", "x", "y"};
and now talk in terms of what tokens you want, by position:
int[] iarr = { 1, 2, 0 };
now you can just use:
foreach (int i in iarr) {
sb.Append(sarr[i]);
}
One possible solution: use a SortedDictionary<int, string> like this:
int iFH = 2, i1R = 0, i2R = 1;
string sFH = "z", s1R = "x", s2R = "y";
var map = new SortedDictionary<int, string>();
map[iFH] = sFH;
map[i1R] = s1R;
map[i2R] = s2R;
var result = string.Join("", map.Values);
If I understand correctly, you mean to use the int values as order number in an array of strings. Since the int values are of type int, you could directly use them as values. For Example, assuming you have an array of strings called stringArray,
stringArray[iFH] = sFH;
Doing this for all the strings you can make an ordered array. To concatenate them all, you can iterate over the array and add them to a seperate string in the following way:
String finalString = "";
for(int i = 0; i < stringArray.Length; i++){
finalString = finalString + stringArray[i];
}
console.WriteLine(finalString);
Splitting the problem into two
Converting an arbitrarily long random list of variables into an
array
Using the array to create a concatenated string
For part 1, create a function that takes params
public static string[] StringList(params object[] stringValues) => stringValues.Cast<string>().ToArray();
public static int[] PositionList(params object[] intValues) => intValues.Cast<int>().ToArray();
For part 2
public static string Join(string[] text, int[] positions)
{
string[] final = new string[text.Length];
for (int i = 0; i < text.Length; i++)
{
final[positions[i]] = text[i];
}
return string.Join("", final);
}
Then run like this:
public static string RunExample()
{
string sFH = "z"; string s1R = "x"; string s2R = "y";
int iFH = 2; int i1R = 0; int i2R = 1;
return Join(StringList(sFH, s1R, s2R), PositionList(iFH, i1R, i2R));
}
Entire example:
public static class Joiner
{
public static string[] StringList(params object[] stringValues) => stringValues.Cast<string>().ToArray();
public static int[] PositionList(params object[] intValues) => intValues.Cast<int>().ToArray();
public static string Join(string[] text, int[] positions)
{
string[] final = new string[text.Length];
for (int i = 0; i < text.Length; i++)
{
final[positions[i]] = text[i];
}
return string.Join("", final);
}
public static string RunExample()
{
string sFH = "z"; string s1R = "x"; string s2R = "y";
int iFH = 2; int i1R = 0; int i2R = 1;
return Join(StringList(sFH, s1R, s2R), PositionList(iFH, i1R, i2R));
}
}
You can add your own code for exception handling (mismatch in array sizes etc).

C# Remove everything after specific word

My input is:
something1#email.com.;;
something2#email.eu,./
something3#email.org..
something4#email.netcdsfsd
What I want is to get rid of all characters after my "domains"(stored in array).
So output should be:
something1#email.com
something2#email.eu
something3#email.org
something4#email.net
My code is:
string[] domains = richTextBox_domains.Text.Split(';');
char[] specialchars = ".!#$%^&*()-_=+[]{}\\|;:'\",.<>/?".ToCharArray();
for (int x = 0; x < domains.Length; x++)
{
for (int y = 0; y < specialchars.Length; y++)
{
string check = domains[x] + specialchars[y];
string aftertmp = "." + after.Substring(after.IndexOf('.') + 1);
if (aftertmp == check)
after = after.Replace(check, domains[x]);
}
}
It's working but not always and only for one character at the end.
I will be glad for help
use regex to check email id and than store it in different array
var regex1 = new Regex("(([-a-zA-Z0-9])|([-a-zA-Z0-9]{1,256}[#%._\+~#=][-a-zA-Z0-9])){1,10}\.[-a-zA-Z0-9]{1,10}\b",RegexOptions.IgnoreCase);
string[] domains = richTextBox_domains.Text.Split(';');
List<string> l = new List<string>();
for (int x = 0; x < domains.Length; x++)
{
var results = regex1.Matches(domains[x]);
foreach (Match match in results)
{
l.Add(match.Groups[1].Value);
MessageBox.Show(match.Groups[1].Value);
}
}
string[] s = l.ToArray();// new array
hope this helps
This works fine
string[] s = { ".com",".net",".edu",".eu" };
string[] domain = new string[]
{
"something1#email.com.;;",
"something2#email.eu,./",
"something3#email.org..",
"something4#email.netcdsfsd"
};
string result = "";
for (int m = 0; m < domain.Length; m++)
{
for (int i = 0; i < s.Length; i++)
{
if (domain[m].IndexOf(s[i]) != -1)
{
result = domain[m].Substring(0, domain[m].IndexOf(s[i])) + s[i];
MessageBox.Show(result);
}
}
}
}

How to Generate formatted Alpha Numeric strings in C#

I want to generate random string with 5 alpha numeric characters, But should generate two characters and other should be numeric like
RL589
For that I have done like
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var stringChars = new char[5];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
But i get confused how to arrange first two letters be characters and next other should be numeric. Please help me anyone.
Generate two strings. One of characters and one of numbers. Then, concatenate them.
Use two loops, for example like this:
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var stringChars = new char[5];
var random = new Random();
for (int i = 0; i < 2; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
for (int i = 2; i < stringChars.Length; i++)
{
stringChars[i] = numbers[random.Next(numbers.Length)];
}
var finalString = new String(stringChars);
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var stringChars = new char[5];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
if (i < 2)
{
stringChars[i] = letters[random.Next(letters.Length)];
}
else
{
stringChars[i] = numbers[random.Next(numbers.Length)];
}
}
var finalString = new String(stringChars);
You don't need any strings. Just use the implicit conversions between char and int:
var stringChars = new char[5];
var random = new Random();
for (int i = 0; i < 2; i++)
{
stringChars[i] = (char)random.Next('A', 'Z');
}
for (int i = 2; i < 5; i++)
{
stringChars[i] = (char)random.Next('0', '9');
}
var finalString = new String(stringChars);
Why don't you just use the Random object to create a random number?
var stringChars = new StringBuilder();
var random = new Random();
for (int i = 0; i < 2; i++)
{
stringChars.Append((char)random.Next('A', 'Z'));
}
var finalString = string.Format("{0}{1}{2}{3}", stringChars.ToString()
, random.Next(1, 9)
, random.Next(1, 9)
, random.Next(1, 9));
or simply
var finalString = string.Format("{0}{1}", stringChars.ToString()
, random.Next(100, 999));
Why StringBuilder, string concatenation always creates a new instance so you should avoid that.

Sorting a list and give each item a new sorting index

Lets say I have 3 menu-items. Each one have (eg) 5 links inside. So I have a something like this:
//This is just some test-code. normally i''ll get the data from a database
List<NavigationModel> navigation = new List<NavigationModel>();
Random randomInt = new Random();
for (int i = 0; i < 5; i++)
{
NavigationModel m = new NavigationModel();
m.MenuName = "Users";
m.LinkName = "Link (" + i + ")";
m.ControllerName = "AAA";
m.ActionName = "Function" + i;
m.SortingMenu = 5;
navigation.Add(m);
}
for (int i = 0; i < 5; i++)
{
NavigationModel m = new NavigationModel();
m.MenuName = "Help";
m.LinkName = "Link (" + i + ")";
m.ControllerName = "BBB";
m.ActionName = "Function" + i;
m.SortingMenu = 10;
navigation.Add(m);
}
for (int i = 0; i < 5; i++)
{
NavigationModel m = new NavigationModel();
m.MenuName = "Home";
m.LinkName = "Link (" + i + ")";
m.ControllerName = "CCC";
m.ActionName = "Function" + i;
m.SortingMenu = 2;
navigation.Add(m);
}
navigation = navigation.OrderBy(x => x.SortingMenu).ToList();
As you can see I'll get 3 menu-items with correct sorting BUT I need the sorting started by 0 followed by 1,2 ...
How can I do this without hardcoding or a database update command?
LukeHennerleys answer is probably of a higher standard but I would rather change the value of SortingMenu with a simple for-loop. This should do the trick if you have the list sorted already.
for (int i = 0; i < navigation.Count; i++)
{
navigation[i].SortingMenu = i;
}
Use Select to bring out indexes after calling OrderBy. Select((x, i)) where i will be your index.
public class TestObject
{
public string A { get; set; }
public int Index { get; set; }
}
public void Example()
{
List<TestObject> testObjects = new List<TestObject>();
testObjects.Add(new TestObject() { A = "B" });
testObjects.Add(new TestObject() { A = "C" });
testObjects.Add(new TestObject() { A = "A" });
var objects = testObjects.OrderBy(x => x.A).Select((x, i) => new TestObject() { A = x.A, Index = i });
}

Adding in IList using for Loop

I'm have list of result as
var attributeresult= " some list of items......";
Now I'm trying to loop form result and adding into IList.but I'm getting only lastly inserting values,but I want to get all the values.
IList<DynamicColumn> idynamicttableColumns = new List<DynamicColumn>();
DynamicColumn dynamictableColumns = new DynamicColumn();
for (int i = 0; i < attributeresult.Count(); i++)
{
dynamictableColumns.Name = attributeresult.ElementAt(i).AttributeName;
dynamictableColumns.Type = attributeresult.ElementAt(i).AttributeSqlType;
dynamictableColumns.IsNullable = false;
idynamicttableColumns.Add(dynamictableColumns);
}
I have to accomplish with for loop only not with for each loop.
Move DynamicColumn dynamictableColumns = new DynamicColumn(); into your loop:
IList<DynamicColumn> idynamicttableColumns = new List<DynamicColumn>();
int count = attributeresult.Count();
for (int i = 0; i < count; i++)
{
var item = attributeresult.ElementAt(i);
DynamicColumn dynamictableColumns = new DynamicColumn();
dynamictableColumns.Name = item .AttributeName;
dynamictableColumns.Type = item .AttributeSqlType;
dynamictableColumns.IsNullable = false;
idynamicttableColumns.Add(dynamictableColumns);
}

Categories