Adding the same items to multiple comboboxes - c#

I have 30 comboboxes and in each one of them I have to add the same items. Is there a faster way to do this than typing the same code all over again for 30 times?
comboBox1.Items.Add("K");
comboBox1.Items.Add("H");
comboBox1.Items.Add("L");
comboBox1.Items.Add("T");
comboBox1.SelectedIndex = 0;
comboBox2.Items.Add("K");
comboBox2.Items.Add("H");
comboBox2.Items.Add("L");
comboBox2.Items.Add("T");
comboBox2.SelectedIndex = 1;
... and so on..

string[] values = new[] { "K", "H", "L", "T" };
foreach(string value in values)
{
combobox1.Items.Add(value);
combobox2.Items.Add(value);
}
Even better, if the ItemsCollection has an AddRange method:
string[] values = new[] { "K", "H", "L", "T" };
combobox1.Items.AddRange(values);
combobox2.Items.AddRange(values);

You can iterate over all comboboxes using OfType method:
int i = 0;
foreach(var cmbBox in this.Controls.OfType<ComboBox>())
{
cmbBox.Items.Add("K");
cmbBox.Items.Add("H");
cmbBox.Items.Add("L");
cmbBox.Items.Add("T");
cmbBox.SelectedIndex = i++;
}

InitComboBox(comboBox1);
InitComboBox(comboBox2);
...
private void InitComboBox(ComboBox cb)
{
cb.Items.Add("K");
cb.Items.Add("H");
cb.Items.Add("L");
cb.Items.Add("T");
cb.SelectedIndex = 0;
}

You add a method FillCombo
void FillCombo(Control ctrl)
{
foreach (ComboBox cb in ctrl.Controls)
{
cb.Items.Add("K");
cb.Items.Add("H");
cb.Items.Add("L");
cb.Items.Add("T");
cb.SelectedIndex = 0;
}
}
To use it :
FillCombo(this);

Related

How to DefultView Rowfilter add new

private void categoryCheckedListBox_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
{
if (e.State==CheckState.Checked)
{
string categoryName = categoryCheckedListBox.Items[e.Index].Value.ToString();
(productListGV.DataSource as DataTable).DefaultView.RowFilter = string.Format("Kata2 LIKE '%{0}%' AND Kata1 LIKE '%{1}%'", categoryName,Cins);
}
else
{
(productListGV.DataSource as DataTable).DefaultView.RowFilter = null;
}
}
Hello Category always sounds different and dynamic. What I want is to add it to the filter for each selected checkbox value. CategoryName can have different value.
I did DefaultView.RowFilter+=.... but is error.
Iterate over categoryCheckedListBox.Items, compose your string.Format String based on the iterations and then pass to the string.Formats Object an array with the checked corresponding strings.
Example:
using System;
using System.Linq;
// Lacking actual data, I made an assumption that Kata concatenated with the key will correspond to the actual column
(productListGV.DataSource as DataTable).DefaultView.RowFilter = string.Join(" AND ", new[] { "a", "b", "c" }.Select((val, key) => $"Kata{key} LIKE '%{val}%'" ));
Or:
using System;
string[] a = new[] { "a", "b", "c" };
string s = String.Empty;
for (int i = 0; i < a.Length; i++) s+= $"Kata{i} LIKE '%{a[i]}%'";
(productListGV.DataSource as DataTable).DefaultView.RowFilter = string.Format(s, a);
I believe you get the picture.

WPF Columns to matrix

I have a WPF DataGrid control with data as in the left image. I am a beginner in WPF and is trying to achieve the right version. I want 'asd/qwe' and 'A/B' to be headers for the rows and columns but they vary in values and numbers and I dont know the names from the start (there may also be a 'C' and a 'zxc').
Is there a way to achieve this?
May be a bit late, and you may have already tried this but the following works for me. Even though there are many loops, it takes care of it in a fast manner.
class Program
{
private static DataTable Table = new DataTable();
static void Main(string[] args)
{
Table.Columns.Add("Col1");
Table.Columns.Add("Col2");
Table.Columns.Add("Col3");
Table.Rows.Add(new object[] { "A", 1, "asd" });
Table.Rows.Add(new object[] { "A", 0, "qwe" });
Table.Rows.Add(new object[] { "B", 1, "asd" });
Table.Rows.Add(new object[] { "B", 1, "qwe" });
Table.Rows.Add(new object[] { "C", 2, "qwe" });
Table.Rows.Add(new object[] { "C", 5, "asd" });
Gen(Table);
}
public class Set
{
public string A { get; set; }
public string B { get; set; }
public object Value { get; set; }
}
public static DataTable Gen(DataTable Tbl)
{
// Build objects
var List = new List<Set>();
foreach(DataRow Row in Tbl.Rows)
{
List.Add(new Set { A = (String)Row["Col1"], B = (String)Row["Col3"],Value = Row["Col2"] });
}
var TableBuild = new DataTable();
TableBuild.Columns.Add("X");
var DistinctColumnDefiners = List.Select(t => t.B).Distinct();
var DistinctRowDefiners = List.Select(t => t.A).Distinct();
for (int i = 0; i < DistinctColumnDefiners.Count(); i++)
{
TableBuild.Columns.Add();
TableBuild.Columns[i + 1].ColumnName = DistinctColumnDefiners.ToArray()[i];
}
for (int i = 0; i < DistinctRowDefiners.Count(); i++)
{
TableBuild.Rows.Add();
TableBuild.Rows[i]["X"] = DistinctRowDefiners.ToArray()[i];
}
for (int i = 0; i < DistinctRowDefiners.Count(); i++)
{
for (int k = 0; k < DistinctColumnDefiners.Count(); k++)
{
TableBuild.Rows[i][DistinctColumnDefiners.ToArray()[k]] = List.Where(t => t.A == (String)TableBuild.Rows[i]["X"] && t.B == (String)DistinctColumnDefiners.ToArray()[k]).Select(f=>f.Value).FirstOrDefault();
}
}
return TableBuild;
}
}
I ended up iterating over each 'qwe', 'asd' to add new columns. Then creating an ExpandoObject for each row with 'qwe' etc as properties.
While this probably is not the best way of solving the issue, it resulted in very few lines of code compared to my other attempts.

Multi string replace

im trying to replace normal text with ascii text in this program:
so a will be replaced by â & ETC.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TextConverter
{
public partial class TextCoverter : Form
{
public TextCoverter()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] normal = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
string[] ascii = { "â", "ß", "ç", "ð", "è", "ƒ", "ģ", "н", "ι", "j", "ќ", "ļ", "м", "и", "ю", "ρ", "Ω", "ѓ", "$", "τ", "ט", "Λ", "ш", "χ", "У", "ź" };
for (int i = 0; i < 26; i++)
{
textBox2.Text = textBox1.Text.Replace(normal[i], ascii[i]);
}
}
}
}
But it doesn't replace with Ascii. Please help.
Since you are writing the result into a variable that is different from the original, only the last letter gets replaced. You should either write to the same box, or write to a temp string, and write it to the second box at the end.
var tmp = textBox1.Text;
for (int i = 0; i < 26; i++)
{
tmp = tmp.Replace(normal[i], ascii[i]);
}
textBox2.Text = tmp;
Generally speaking, this is not the most efficient algorithm to do replacements, because it operates on an immutable string. You would be better off creating a mutable string builder, and writing it one character at a time.
const string repl = "âßçðèƒģнιjќļмиюρΩѓ$τטΛшχУź";
var res = new StringBuilder();
foreach (char c in textBox1.Text) {
if (c >= 'a' && c <= 'z') {
res.Append(repl[c-'a']);
} else {
res.Append(c);
}
}
textBox2.Text = res.ToString();
textBox2.Text = textBox1.Text.Replace(normal[i], ascii[i]);
you replace textBox1 again and again, but not save previos state, so work only last loop iteration

How to check whether a word is composed of other strings in an array

I want to check whether a string is built from another two strings within a given string set.
For example, given the following array:
var arr = new string[] { "b", "at", "bat", "ct", "ll", "ball", "ba"};
I want to return only "bat" and "ball".
That's because they can be composed from two other elements in the array like so:
"bat" = "b" + "at"
"ball" = "ba" + "ll"
I have tried doing it with a foreach loop, but I'm not quite getting it right.
Any help will be much appreciated.
I have done something like
foreach(var x in list)
{
if (dataaccess.IsThreeCharacters(x))
{
for (int i = 0; i < arr.Length; i++)
{
for (int j = i; j < arr.Length; j++)
{
if(x == arr[i] + arr[j])
{
newlist.Add(x);
}
}
}
}
}
This will give you all of the values that can be composed from other values in the sequence:
var values = new HashSet<string>(new[] { "b", "at", "bat", "ct", "ll", "ball", "ba" });
var compositeValues =
from value in values
from otherValue in values
where value != otherValue
let compositeValue = value + otherValue
where values.Contains(compositeValue)
select compositeValue;
Notice the use of HashSet<string>, which gives O(1) lookup performance, as opposed to the O(N) of an array.
This should work although I'm not vouching for efficiency!
static void Main(string[] args)
{
var arr = new string[] { "b", "at", "bat", "ct", "ll", "ball", "ba" };
var composites = from s in arr
from lhs in arr
from rhs in arr
where s == string.Concat(lhs, rhs)
select s;
foreach (var composite in composites)
{
Console.WriteLine(composite);
}
Console.ReadLine();
}

C# Permutation of an array of arraylists?

I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.
EXAMPLE: (all values are strings)
myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };
The count of myList can be varied so its length is not known beforehand.
I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).
1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93
Does this make sense of what I am trying to accomplish? I can't seem to come up with a good method for doing this, (if any).
Edit:
I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.
I want to end up building a string[] array of all the combinations that follows the format like below:
for the "1 2 93" permutation
I want the output to be "val0=1;val1=2;val2=93;"
I will experiment with recursion for now. Thank you DrJokepu
I'm surprised nobody posted the LINQ solution.
from val0 in new []{ "1", "5", "3", "9" }
from val1 in new []{ "2", "3" }
from val2 in new []{ "93" }
select String.Format("val0={0};val1={1};val2={2}", val0, val1, val2)
Recursive solution
static List<string> foo(int a, List<Array> x)
{
List<string> retval= new List<string>();
if (a == x.Count)
{
retval.Add("");
return retval;
}
foreach (Object y in x[a])
{
foreach (string x2 in foo(a + 1, x))
{
retval.Add(y.ToString() + " " + x2.ToString());
}
}
return retval;
}
static void Main(string[] args)
{
List<Array> myList = new List<Array>();
myList.Add(new string[0]);
myList.Add(new string[0]);
myList.Add(new string[0]);
myList[0] = new string[]{ "1", "5", "3", "9" };
myList[1] = new string[] { "2", "3" };
myList[2] = new string[] { "93" };
foreach (string x in foo(0, myList))
{
Console.WriteLine(x);
}
Console.ReadKey();
}
Note that it would be pretty easy to return a list or array instead of a string by changing the return to be a list of lists of strings and changing the retval.add call to work with a list instead of using concatenation.
How it works:
This is a classic recursive algorithm. The base case is foo(myList.Count, myList), which returns a List containing one element, the empty string. The permutation of a list of n string arrays s1, s2, ..., sN is equal to every member of sA1 prefixed to the permutation of n-1 string arrays, s2, ..., sN. The base case is just there to provide something for each element of sN to be concatenated to.
I recently ran across a similar problem in a project of mine and stumbled on this question. I needed a non-recursive solution that could work with lists of arbitrary objects. Here's what I came up with. Basically I'm forming a list of enumerators for each of the sub-lists and incrementing them iteratively.
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<IEnumerable<T>> lists)
{
// Check against an empty list.
if (!lists.Any())
{
yield break;
}
// Create a list of iterators into each of the sub-lists.
List<IEnumerator<T>> iterators = new List<IEnumerator<T>>();
foreach (var list in lists)
{
var it = list.GetEnumerator();
// Ensure empty sub-lists are excluded.
if (!it.MoveNext())
{
continue;
}
iterators.Add(it);
}
bool done = false;
while (!done)
{
// Return the current state of all the iterator, this permutation.
yield return from it in iterators select it.Current;
// Move to the next permutation.
bool recurse = false;
var mainIt = iterators.GetEnumerator();
mainIt.MoveNext(); // Move to the first, succeeds; the main list is not empty.
do
{
recurse = false;
var subIt = mainIt.Current;
if (!subIt.MoveNext())
{
subIt.Reset(); // Note the sub-list must be a reset-able IEnumerable!
subIt.MoveNext(); // Move to the first, succeeds; each sub-list is not empty.
if (!mainIt.MoveNext())
{
done = true;
}
else
{
recurse = true;
}
}
}
while (recurse);
}
}
You could use factoradics to generate the enumeration of permutations. Try this article on MSDN for an implementation in C#.
This will work no matter how many arrays you add to your myList:
static void Main(string[] args)
{
string[][] myList = new string[3][];
myList[0] = new string[] { "1", "5", "3", "9" };
myList[1] = new string[] { "2", "3" };
myList[2] = new string[] { "93" };
List<string> permutations = new List<string>(myList[0]);
for (int i = 1; i < myList.Length; ++i)
{
permutations = RecursiveAppend(permutations, myList[i]);
}
//at this point the permutations variable contains all permutations
}
static List<string> RecursiveAppend(List<string> priorPermutations, string[] additions)
{
List<string> newPermutationsResult = new List<string>();
foreach (string priorPermutation in priorPermutations)
{
foreach (string addition in additions)
{
newPermutationsResult.Add(priorPermutation + ":" + addition);
}
}
return newPermutationsResult;
}
Note that it's not really recursive. Probably a misleading function name.
Here is a version that adheres to your new requirements. Note the section where I output to console, this is where you can do your own formatting:
static void Main(string[] args)
{
string[][] myList = new string[3][];
myList[0] = new string[] { "1", "5", "3", "9" };
myList[1] = new string[] { "2", "3" };
myList[2] = new string[] { "93" };
List<List<string>> permutations = new List<List<string>>();
foreach (string init in myList[0])
{
List<string> temp = new List<string>();
temp.Add(init);
permutations.Add(temp);
}
for (int i = 1; i < myList.Length; ++i)
{
permutations = RecursiveAppend(permutations, myList[i]);
}
//at this point the permutations variable contains all permutations
foreach (List<string> list in permutations)
{
foreach (string item in list)
{
Console.Write(item + ":");
}
Console.WriteLine();
}
}
static List<List<string>> RecursiveAppend(List<List<string>> priorPermutations, string[] additions)
{
List<List<string>> newPermutationsResult = new List<List<string>>();
foreach (List<string> priorPermutation in priorPermutations)
{
foreach (string addition in additions)
{
List<string> priorWithAddition = new List<string>(priorPermutation);
priorWithAddition.Add(addition);
newPermutationsResult.Add(priorWithAddition);
}
}
return newPermutationsResult;
}
What you are asking for is called the Cartesian Product. Once you know what its called, there are several similar questions on Stack Overflow. They all seem to end up pointing to an answer which ended up written as a blog post:
http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
Non-recursive solution:
foreach (String s1 in array1) {
foreach (String s2 in array2) {
foreach (String s3 in array3) {
String result = s1 + " " + s2 + " " + s3;
//do something with the result
}
}
}
Recursive solution:
private ArrayList<String> permute(ArrayList<ArrayList<String>> ar, int startIndex) {
if (ar.Count == 1) {
foreach(String s in ar.Value(0)) {
ar.Value(0) = "val" + startIndex + "=" + ar.Value(0);
return ar.Value(0);
}
ArrayList<String> ret = new ArrayList<String>();
ArrayList<String> tmp1 ar.Value(0);
ar.remove(0);
ArrayList<String> tmp2 = permute(ar, startIndex+1);
foreach (String s in tmp1) {
foreach (String s2 in tmp2) {
ret.Add("val" + startIndex + "=" + s + " " + s2);
}
}
return ret;
}
Here is a generic recursive function that I wrote (and an overload that may be convenient to call):
Public Shared Function GetCombinationsFromIEnumerables(ByRef chain() As Object, ByRef IEnumerables As IEnumerable(Of IEnumerable(Of Object))) As List(Of Object())
Dim Combinations As New List(Of Object())
If IEnumerables.Any Then
For Each v In IEnumerables.First
Combinations.AddRange(GetCombinationsFromIEnumerables(chain.Concat(New Object() {v}).ToArray, IEnumerables.Skip(1)).ToArray)
Next
Else
Combinations.Add(chain)
End If
Return Combinations
End Function
Public Shared Function GetCombinationsFromIEnumerables(ByVal ParamArray IEnumerables() As IEnumerable(Of Object)) As List(Of Object())
Return GetCombinationsFromIEnumerables(chain:=New Object() {}, IEnumerables:=IEnumerables.AsEnumerable)
End Function
And the equivalent in C#:
public static List<object[]> GetCombinationsFromIEnumerables(ref object[] chain, ref IEnumerable<IEnumerable<object>> IEnumerables)
{
List<object[]> Combinations = new List<object[]>();
if (IEnumerables.Any) {
foreach ( v in IEnumerables.First) {
Combinations.AddRange(GetCombinationsFromIEnumerables(chain.Concat(new object[] { v }).ToArray, IEnumerables.Skip(1)).ToArray);
}
} else {
Combinations.Add(chain);
}
return Combinations;
}
public static List<object[]> GetCombinationsFromIEnumerables(params IEnumerable<object>[] IEnumerables)
{
return GetCombinationsFromIEnumerables(chain = new object[], IEnumerables = IEnumerables.AsEnumerable);
}
Easy to use:
Dim list1 = New String() {"hello", "bonjour", "hallo", "hola"}
Dim list2 = New String() {"Erwin", "Larry", "Bill"}
Dim list3 = New String() {"!", ".."}
Dim result = MyLib.GetCombinationsFromIEnumerables(list1, list2, list3)
For Each r In result
Debug.Print(String.Join(" "c, r))
Next
or in C#:
object list1 = new string[] {"hello","bonjour","hallo","hola"};
object list2 = new string[] {"Erwin", "Larry", "Bill"};
object list3 = new string[] {"!",".."};
object result = MyLib.GetCombinationsFromIEnumerables(list1, list2, list3);
foreach (r in result) {
Debug.Print(string.Join(' ', r));
}
Here is a version which uses very little code, and is entirely declarative
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> collection) where T : IComparable
{
if (!collection.Any())
{
return new List<IEnumerable<T>>() {Enumerable.Empty<T>() };
}
var sequence = collection.OrderBy(s => s).ToArray();
return sequence.SelectMany(s => GetPermutations(sequence.Where(s2 => !s2.Equals(s))).Select(sq => (new T[] {s}).Concat(sq)));
}
class Program
{
static void Main(string[] args)
{
var listofInts = new List<List<int>>(3);
listofInts.Add(new List<int>{1, 2, 3});
listofInts.Add(new List<int> { 4,5,6 });
listofInts.Add(new List<int> { 7,8,9,10 });
var temp = CrossJoinLists(listofInts);
foreach (var l in temp)
{
foreach (var i in l)
Console.Write(i + ",");
Console.WriteLine();
}
}
private static IEnumerable<List<T>> CrossJoinLists<T>(IEnumerable<List<T>> listofObjects)
{
var result = from obj in listofObjects.First()
select new List<T> {obj};
for (var i = 1; i < listofObjects.Count(); i++)
{
var iLocal = i;
result = from obj in result
from obj2 in listofObjects.ElementAt(iLocal)
select new List<T>(obj){ obj2 };
}
return result;
}
}
Here's a non-recursive, non-Linq solution. I can't help feeling like I could have less looping and calculate the positions with division and modulo, but can't quite wrap my head around that.
static void Main(string[] args)
{
//build test list
List<string[]> myList = new List<string[]>();
myList.Add(new string[0]);
myList.Add(new string[0]);
myList.Add(new string[0]);
myList[0] = new string[] { "1", "2", "3"};
myList[1] = new string[] { "4", "5" };
myList[2] = new string[] { "7", "8", "9" };
object[][] xProds = GetProducts(myList.ToArray());
foreach(object[] os in xProds)
{
foreach(object o in os)
{
Console.Write(o.ToString() + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
static object[][] GetProducts(object[][] jaggedArray){
int numLists = jaggedArray.Length;
int nProducts = 1;
foreach (object[] oArray in jaggedArray)
{
nProducts *= oArray.Length;
}
object[][] productAry = new object[nProducts][];//holds the results
int[] listIdxArray = new int[numLists];
listIdxArray.Initialize();
int listPtr = 0;//point to current list
for(int rowcounter = 0; rowcounter < nProducts; rowcounter++)
{
//create a result row
object[] prodRow = new object[numLists];
//get values for each column
for(int i=0;i<numLists;i++)
{
prodRow[i] = jaggedArray[i][listIdxArray[i]];
}
productAry[rowcounter] = prodRow;
//move the list pointer
//possible states
// 1) in a list, has room to move down
// 2) at bottom of list, can move to next list
// 3) at bottom of list, no more lists left
//in a list, can move down
if (listIdxArray[listPtr] < (jaggedArray[listPtr].Length - 1))
{
listIdxArray[listPtr]++;
}
else
{
//can move to next column?
//move the pointer over until we find a list, or run out of room
while (listPtr < numLists && listIdxArray[listPtr] >= (jaggedArray[listPtr].Length - 1))
{
listPtr++;
}
if (listPtr < listIdxArray.Length && listIdxArray[listPtr] < (jaggedArray[listPtr].Length - 1))
{
//zero out the previous stuff
for (int k = 0; k < listPtr; k++)
{
listIdxArray[k] = 0;
}
listIdxArray[listPtr]++;
listPtr = 0;
}
}
}
return productAry;
}
One of the problems I encountred when I was doing this for a very large amount of codes was that with the example brian was given I actually run out of memory. To solve this I used following code.
static void foo(string s, List<Array> x, int a)
{
if (a == x.Count)
{
// output here
Console.WriteLine(s);
}
else
{
foreach (object y in x[a])
{
foo(s + y.ToString(), x, a + 1);
}
}
}
static void Main(string[] args)
{
List<Array> a = new List<Array>();
a.Add(new string[0]);
a.Add(new string[0]);
a.Add(new string[0]);
a[0] = new string[] { "T", "Z" };
a[1] = new string[] { "N", "Z" };
a[2] = new string[] { "3", "2", "Z" };
foo("", a, 0);
Console.Read();
}
private static void GetP(List<List<string>> conditions, List<List<string>> combinations, List<string> conditionCombo, List<string> previousT, int selectCnt)
{
for (int i = 0; i < conditions.Count(); i++)
{
List<string> oneField = conditions[i];
for (int k = 0; k < oneField.Count(); k++)
{
List<string> t = new List<string>(conditionCombo);
t.AddRange(previousT);
t.Add(oneField[k]);
if (selectCnt == t.Count )
{
combinations.Add(t);
continue;
}
GetP(conditions.GetRange(i + 1, conditions.Count - 1 - i), combinations, conditionCombo, t, selectCnt);
}
}
}
List<List<string>> a = new List<List<string>>();
a.Add(new List<string> { "1", "5", "3", "9" });
a.Add(new List<string> { "2", "3" });
a.Add(new List<string> { "93" });
List<List<string>> result = new List<List<string>>();
GetP(a, result, new List<string>(), new List<string>(), a.Count);
Another recursive function.

Categories