There are two sets of:
int Transformer substations
object Buildings(the set is larger than the first set at least by 5 times).
The building has 2 parameters (number and load).
Need to create all possible combinations: each transformer station is loaded by 60-80% in every combination, and buildings don't repeat.
Glad to hear any suggestions.
Tried the Cartesian product but I have no idea how to apply it. Ideas just don't appear. I guess it is because of the stress produced by the war in Ukraine where I live.
A cartesian product without elements repetition in any given result set and without permutations:
static void combinations(List<List<string>> srs, int[] size, List<string> curr, int index)
{
if (index == srs.Count())
{
int s = curr.Count();
string[] d = new string[s];
List<string> x = d.ToList();
x.AddRange(curr);
x.RemoveAll(item => item == null);
dest.Add(x);
string res = "";
foreach (var item in x)
{
res += item + ", ";
}
//dest.add(d);
Console.WriteLine(res);
}
else
{
for (int i = 0; i < size[index]; i++)
{
int n = size[index];
string[] dim = new string[n];
dim = srs[index].ToArray();
curr.Add(dim[i]);
index++;
combinations(srs, size, curr, index);
index--;
curr.RemoveAt(curr.Count() - 1);
}
}
}
public static void init()
{
string[] confidence = new string[] { "High", "Low Variable" };
string[] goalspec = new string[] { "High", "Low Some" };
string[] quality = new string[] { "High", "Low Variable" };
string[] tansSkills = new string[] { "High", "Low some" };
string[] sitLead = new string[] { "S1", "S2", "S3", "S4" };
string[] devLev = new string[] { "D1", "D2", "D3", "D4" };
string[] statReason = new string[] {"In backlog", "Canceled", "Completed" };
List<List<string>> srs = new List<List<string>>
{
confidence.ToList(),
goalspec.ToList(),
quality.ToList(),
tansSkills.ToList(),
sitLead.ToList(),
devLev.ToList(),
statReason.ToList()
};
number_elem = srs.Count();
int[] size = new int[number_elem];
size[0] = confidence.Count();
size[1] = goalspec.Count();
size[2] = quality.Count();
size[3] = tansSkills.Count();
size[4] = sitLead.Count();
size[5] = devLev.Count();
size[6] = statReason.Count();
dest = new List<List<string>>();
List<string> curr = new List<string>();
combinations(srs, size, curr, 0);
}
I am receiving a string reply from serial port and this reply contains 3 different value. Every value is separated with ';'.
For example;
10;155.4587;0.01
I need to separate these values and add to a Listview box.
I've found examples of Split(';') function but i think it is not possible to assign split values to different arrays.
Is there any way to perform this extraction with using/not using split() function?
Thanks in advance for any help.
Assuming an array of input strings...
string[] a1 = new string[] {
"10; 155.4587; 0.01",
"20; 255.4587; 0.02",
"30; 355.4587; 0.03",
};
List<string> r1 = new List<string>();
List<string> r2 = new List<string>();
List<string> r3 = new List<string>();
foreach (string t1 in a1)
{
string[] t2 = t1.Split(";");
r1.Add(t2[0]);
r2.Add(t2[1]);
r3.Add(t2[2]);
}
There's a wide variety of methods to doing this, you could use a Regex to delimit each item and use Lambda functions.
You could do something more basic like manipulating the below drawn-out example:
string s = "10;155.4587;0.01";
string[] a = new String[1];
string[] b = new String[1];
string[] c = new String[1];
string[] z = s.Split(';');
for(int i=0; i< z.Length; i++)
{
switch(i)
{
case 0:
a[0] = z[i];
break;
case 1:
b[0] = z[i];
break;
case 2:
c[0] = z[i];
break;
}
}
Console.WriteLine(a[0] + ' ' + b[0] + ' ' + c[0]);
The above illustrates how to manipulate elements but doesn't scale exactly well you may wish to pursue the anonymous route with the first comment using lambdas (see mukesh kudi's answer).
You can get this with help of linq...
string s = "10;155.4587;0.01";
var arrList = s.Split(';').Select(x => new string[] { x }).ToArray();
Here arrList contains three arrays. but i am not sure how this will help you. if you want to bind this result with ListView you have to traverse this collection and get each array value and bind to listview. you can do this with single array by traverse it's index's.
EDIT
To add just one list view item use:
var s = "10;155.4587;0.01";
var values = s.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var listViewItem = new ListViewItem(values[0]);
listViewItem.SubItems.Add(values[1]);
listViewItem.SubItems.Add(values[2]);
listView1.Items.Add(listViewItem);
Assuming you have multiple strings to populate the listBox, try:
ListView listView1 = new ListView();
listView1.Bounds = new Rectangle(new Point(10, 10), new Size(300, 200));
listView1.View = View.Details;
listView1.GridLines = true;
listView1.Columns.Add("TD");
listView1.Columns.Add("AD");
listView1.Columns.Add("CT", -2);
var sValues = new string[] { "10;155.4587;0.01", "11;156.4587;0.02", "12;157.4587;0.03" };
var values = sValues.Select(x => x.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
.Select(x =>
{
var listViewItem = new ListViewItem(x[0]);
listViewItem.SubItems.Add(x[1]);
listViewItem.SubItems.Add(x[2]);
return listViewItem;
});
listView1.Items.AddRange(values.ToArray());
Thanks for all the help.
With the suggestion of #Captain Wibble, i successfully decoded my replies and add to Listview item.
Here is what i did for anyone in same trouble;
First i added my data packages "\r\n"
10;12.2345;0.01\r\n
I used;
serial.ReadLine()
Function to receive incoming data.
To decode and store the data into a listview object i use;
var s = text;
string[] a = new String[3];
//string[] b = new String[1];
//string[] c = new String[1];
string[] z = s.Split(';');
for (int i = 0; i < z.Length; i++)
{
switch (i)
{
case 0:
a[0] = z[i];
break;
case 1:
a[1] = z[i];
break;
case 2:
a[2] = z[i];
break;
}
}
itm = new ListViewItem(a);
listView5.Items.Add(itm);
What are all the array initialization syntaxes that are possible with C#?
These are the current declaration and initialization methods for a simple array.
string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2
Note that other techniques of obtaining arrays exist, such as the Linq ToArray() extensions on IEnumerable<T>.
Also note that in the declarations above, the first two could replace the string[] on the left with var (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. So if you're into the whole brevity thing, the above could be written as
var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2
The array creation syntaxes in C# that are expressions are:
new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }
In the first one, the size may be any non-negative integral value and the array elements are initialized to the default values.
In the second one, the size must be a constant and the number of elements given must match. There must be an implicit conversion from the given elements to the given array element type.
In the third one, the elements must be implicitly convertible to the element type, and the size is determined from the number of elements given.
In the fourth one the type of the array element is inferred by computing the best type, if there is one, of all the given elements that have types. All the elements must be implicitly convertible to that type. The size is determined from the number of elements given. This syntax was introduced in C# 3.0.
There is also a syntax which may only be used in a declaration:
int[] x = { 10, 20, 30 };
The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.
there isn't an all-in-one guide
I refer you to C# 4.0 specification, section 7.6.10.4 "Array Creation Expressions".
Non-empty arrays
var data0 = new int[3]
var data1 = new int[3] { 1, 2, 3 }
var data2 = new int[] { 1, 2, 3 }
var data3 = new[] { 1, 2, 3 }
var data4 = { 1, 2, 3 } is not compilable. Use int[] data5 = { 1, 2, 3 } instead.
Empty arrays
var data6 = new int[0]
var data7 = new int[] { }
var data8 = new [] { } and int[] data9 = new [] { } are not compilable.
var data10 = { } is not compilable. Use int[] data11 = { } instead.
As an argument of a method
Only expressions that can be assigned with the var keyword can be passed as arguments.
Foo(new int[2])
Foo(new int[2] { 1, 2 })
Foo(new int[] { 1, 2 })
Foo(new[] { 1, 2 })
Foo({ 1, 2 }) is not compilable
Foo(new int[0])
Foo(new int[] { })
Foo({}) is not compilable
Enumerable.Repeat(String.Empty, count).ToArray()
Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.
In case you want to initialize a fixed array of pre-initialized equal (non-null or other than default) elements, use this:
var array = Enumerable.Repeat(string.Empty, 37).ToArray();
Also please take part in this discussion.
var contacts = new[]
{
new
{
Name = " Eugene Zabokritski",
PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
},
new
{
Name = " Hanying Feng",
PhoneNumbers = new[] { "650-555-0199" }
}
};
Example to create an array of a custom class
Below is the class definition.
public class DummyUser
{
public string email { get; set; }
public string language { get; set; }
}
This is how you can initialize the array:
private DummyUser[] arrDummyUser = new DummyUser[]
{
new DummyUser{
email = "abc.xyz#email.com",
language = "English"
},
new DummyUser{
email = "def#email.com",
language = "Spanish"
}
};
Just a note
The following arrays:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };
Will be compiled to:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };
Repeat without LINQ:
float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
int[] array = new int[4];
array[0] = 10;
array[1] = 20;
array[2] = 30;
or
string[] week = new string[] {"Sunday","Monday","Tuesday"};
or
string[] array = { "Sunday" , "Monday" };
and in multi dimensional array
Dim i, j As Integer
Dim strArr(1, 2) As String
strArr(0, 0) = "First (0,0)"
strArr(0, 1) = "Second (0,1)"
strArr(1, 0) = "Third (1,0)"
strArr(1, 1) = "Fourth (1,1)"
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
Another way of creating and initializing an array of objects. This is similar to the example which #Amol has posted above, except this one uses constructors. A dash of polymorphism sprinkled in, I couldn't resist.
IUser[] userArray = new IUser[]
{
new DummyUser("abc#cde.edu", "Gibberish"),
new SmartyUser("pga#lna.it", "Italian", "Engineer")
};
Classes for context:
interface IUser
{
string EMail { get; } // immutable, so get only an no set
string Language { get; }
}
public class DummyUser : IUser
{
public DummyUser(string email, string language)
{
m_email = email;
m_language = language;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
}
public class SmartyUser : IUser
{
public SmartyUser(string email, string language, string occupation)
{
m_email = email;
m_language = language;
m_occupation = occupation;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
private string m_occupation;
}
For the class below:
public class Page
{
private string data;
public Page()
{
}
public Page(string data)
{
this.Data = data;
}
public string Data
{
get
{
return this.data;
}
set
{
this.data = value;
}
}
}
you can initialize the array of above object as below.
Pages = new Page[] { new Page("a string") };
Hope this helps.
hi just to add another way:
from this page :
https://learn.microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1
you can use this form If you want to Generates a sequence of integral numbers within a specified range strat 0 to 9:
using System.Linq
.....
public int[] arrayName = Enumerable.Range(0, 9).ToArray();
You can also create dynamic arrays i.e. you can first ask the size of the array from the user before creating it.
Console.Write("Enter size of array");
int n = Convert.ToInt16(Console.ReadLine());
int[] dynamicSizedArray= new int[n]; // Here we have created an array of size n
Console.WriteLine("Input Elements");
for(int i=0;i<n;i++)
{
dynamicSizedArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Elements of array are :");
foreach (int i in dynamicSizedArray)
{
Console.WriteLine(i);
}
Console.ReadKey();
Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.
NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback
To initialize an empty array, it should be Array.Empty<T>() in dotnet 5.0
For string
var items = Array.Empty<string>();
For number
var items = Array.Empty<int>();
Another way is by calling a static function (for a static object) or any function for instance objects. This can be used for member initialisation.
Now I've not tested all of this so I'll put what I've tested (static member and static function)
Class x {
private static Option[] options = GetOptionList();
private static Option[] GetOptionList() {
return (someSourceOfData).Select(dataitem => new Option()
{field=dataitem.value,field2=dataitem.othervalue});
}
}
What I'd love to know is if there is a way to bypass the function declaration. I know in this example it could be used directly, but assume the function is a little more complex and can't be reduced to a single expression.
I imagine something like the following (but it doesn't work)
Class x {
private static Option[] options = () => {
Lots of prep stuff here that means we can not just use the next line
return (someSourceOfData).Select(dataitem => new Option()
{field=dataitem.value,field2=dataitem.othervalue});
}
}
Basically a way of just declaring the function for the scope of filling the variable.
I'd love it if someone can show me how to do that.
For multi-dimensional array in C# declaration & assign values.
public class Program
{
static void Main()
{
char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };
int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
}
}
Let's say I have a list of arrays with contains as below:
var listArray = new List<string[]>():
1st array = {code, ID_1, PK_1, ID_2, PK_2} //Somehow like a header
2nd array = {85734, 32343, 1, 66544, 2}
3rd array = {59382, 23324, 1, 56998, 2}
4rd array = {43234, 45334, 1, 54568, 2}
and these arrays will be added into 'listArray'.
listArray.Add(array);
what should I do for matching the variable inside the list?
e.g: if ID_1 of the array is '32343', ID_2 = '66544'.
// create
var listArray = new List<string[]>():
string whatIWantToFind = "1234";
string[] mySearchArray = new string[] {"1234", "234234", "324234"};
// fill your array here...
// search
foreach(string[] listItem in listArray)
{
// if you want to check a single item inside...
foreach(string item in listItem)
{
// you can compare
if(item == whatIWantToFind)
{
}
// or check if it contains
if(item.Contains(whatIWantToFind))
{
}
}
// to compare everything..
bool checked = true;
for(int i = 0; i < listItem.lenght; i++)
{
if(!listItem[i].Equals(mySearchArray[i])
{
checked = false; break;
}
}
// aha! this is the one
if(checked) {}
}
If you create a class that contains all the data for one array, you can make a master array of those objects. For instance:
public class ListItem {
public string code, ID_1, PK_1, ID_2, PK_2;
}
And then you can use this class:
var listArray = new List<ListItem>();
listArray.add(new ListItem(){ code = 85734, ID_1 = 32343, PK_1 = 1, ID_2 = 66544, PK_2 = 2});
listArray.add(......);
Then, to find the data, you can use a field accessor on the objects in the array:
foreach(var item in listArray)
{
if (item.ID_1.equals("32343") && item.ID_2.equals("66544"))
Console.WriteLine("Found item.");
}
var listArray = new List<string[]>
{
new []{ "code", "ID_1", "PK_1", "ID_2", "PK_2"},
new []{ "85734", "32343", "1", "66544", "2"},
new []{"59382", "23324", "1", "56998", "2"}
};
var index = listArray.First().ToList().IndexOf("ID_1");
var result = listArray.Where((a, i) => i > 0 && a[index] == "32343").ToList();
I have 2 string arrays. The one is the base and the other is changing.
string[] baseArray = { "Gold", "Silver", "Bronze" };
string[] readArray = { "Bronze", "Silver", "Gold" };
// After comparing the readArray over the baseArray the result should be this
//string match = "Gold";
I want to get the 1st in order of the baseArray.
//Example2
string[] readArray = { "Bronze", "Silver" };
//string match should be "Silver"
If you only want one result, using LINQ:
string firstMatch = baseArray.FirstOrDefault(readArray.Contains);
If you only want one result, not using LINQ:
string firstMatch = null;
foreach(string element in baseArray)
{
if (Array.IndexOf(readArray, element) >= 0)
{
firstMatch = element;
break;
}
}
If you want all matching elements, using LINQ:
string[] common = baseArray.Intersect(readArray).ToArray();
If you want all matching elements, not using LINQ:
HasSet<string> common = new HashSet<string>(readArray);
result.Intersect(baseArray);
var match = baseArray.FirstOrDefault(x => readArray.Contains(x));