Dividing items into columns - c#

I have a dynamic number of items to divide into a maximum of 4 columns, with the proper html format surrounding then, lets say:
string[] s = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }; // from 1 to n itens
To format into this html:
<ul>
<li>
1
2
3
</li>
<li>
4
5
</li>
<li>
6
7
</li>
<li>
8
9
</li>
</ul>
Edit: my website problem:
If you have words as itens, putting the itens this way will organize the words into alphabetically columns (people read this way), not alphabetically rows. Like:
a d g i
b e h j
c f
Instead of:
a b c d
e f g h
i j

Assuming that you want to evenly distribute any remainders, this will do the job:
string[] s = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
// create the 4 buckets with equal distribution
var buckets = Enumerable.Repeat(s.Length / 4, 4).ToArray();
// distribute any remainders evenly starting from the first bucket
var rem = s.Length % 4;
for (var i = 0; i < rem; i++) buckets[i]++;
var idx = 0;
Console.WriteLine("<ul>");
foreach (var bucket in buckets)
{
Console.WriteLine("\t<li>");
foreach (var _ in Enumerable.Range(1, bucket))
{
Console.WriteLine("\t\t{0}", s[idx++]);
}
Console.WriteLine("\t</li>");
}
Console.WriteLine("</ul>");
For the above code, here is what some edge cases return.
{} = 4 empty items in list
{ "1", "2", "3"} = 1, 2, 3 in the first three items, fourth item empty
{ "1", "2", "3", "4", "5"} = 1, 2 in the first item, 3, 4, 5 in the other items

Just loop over the array distributing the array items with a few if statements within it.
int j = 0;
for (int i = 0; i < s.Length; i++)
{
if (j == 0)
// put s[i] in column 1 j = j +1
else if (j == 1)
// put s[i] in column 2 j = j +1
else if (j == 2)
// put s[i] in column 3 j = j +1
if (j == 3)
// put s[i] in column 4 set j = 0
}

Since you want to group by columns instead of rows, just realize that you're ultimately going to have to do SOMETHING with the index. The easiest way to do this is to transform the items into Item/Index pairs and group by those indexes somehow.
s.Select((tr, ti) => new { Index = ti, Item = tr })
.GroupBy(tr => tr.Index % SOME_MAGIC_NUMBER)
If you want to instead group by rows, change the % operator to a division / and you'll be set. This will now take all your items and group them into the however many items you specify (based on either row or column). To transform them, all you have to do is another select:
.Select(tr => "<li>" + string.Join(" ", tr.Select(tstr => tstr.Item.ToString()).ToArray()) + "</li>")
This will get you a list of all your list items in whatever format you want. If you want to include <br /> between the elements of each <li> then just change the first argument of the string.Join call.

Related

Splitting String Arrays into Groups

There is a string [] yield that can contain N count data. I have defined 15 count to be an example.
I want to divide these data into 6 groups.However, I cannot load the last remaining items into the array.
Where am I making a mistake?
string[] tags = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"};
double tagLength = (int)Math.Floor(tags.Length / (double)6);
for (int i = 0; i <= tagLength-1; i++)
{
string[] groupArrays = new string[6];
Array.Copy(tags, i * 6, groupArrays, 0, 6);
}
The output i see
[0] = {1,2,3,4,5,6}
[1] = {7,8,9,10,11,12}
Should be output
[0] = {1,2,3,4,5,6}
[1] = {7,8,9,10,11,12}
[2] = {13,14,15}
I would suggest changing your code to calculate the number of groups you need to this:
int groups = (count / groupSize);
bool hasPartialGroup = count % groupSize != 0;
if (hasPartialGroup)
{
++groups;
}
The result of the first line will be integer division, so 15 / 6 will result in 2. We then see if there is a remainder using the remainder operator (%): count % groupSize. If its result isn't 0, then there is a remainder, and we have a partial group, so we have to account for that.
So for groups = 15 and groupSize = 6, we'll get count = 3. For groups = 12 and groupSize = 6, we'll get count = 2, etc.
Fixing your code to use this, it might look like:
string[] tags = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"};
int count = tags.Length;
const int groupSize = 6;
int groups = (count / groupSize);
bool hasPartialGroup = count % groupSize != 0;
if (hasPartialGroup)
{
++groups;
}
for (int i = 0; i < groups; i++)
{
// you can't copy beyond the end of the array so we have to choose between the remaining ungrouped items and the group size
int currentGroupSize = Math.Min(tags.Length - i*groupSize, groupSize);
// I'm assuming for a partial group you only want this to be as big as the number of items.
// If you want it to always be 6 then change new string[currentGroupSize] to new string[groupSize] and you should be OK.
string[] groupArrays = new string[currentGroupSize];
Array.Copy(tags, i * groupSize, groupArrays, 0, currentGroupSize);
Console.WriteLine(string.Join(",", groupArrays));
}
Try it online // Example with fixed group size
Alternatively, you could create a batching helper method:
private static IEnumerable<T[]> BatchItems<T>(IEnumerable<T> source, int batchSize)
{
var collection = new List<T>(batchSize);
foreach (var item in source)
{
collection.Add(item);
if (collection.Count == batchSize)
{
yield return collection.ToArray();
collection.Clear();
}
}
if (collection.Count > 0)
{
yield return collection.ToArray();
}
}
This will collect batchSize number items together and then return one group at a time. You can read about how this works with yield return here.
Usage:
string[] tags = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"};
List<string[]> batchedTags = BatchItems(tags, 6).ToList();
This will result in 3 string arrays, containing 1,2,3,4,5,6, 7,8,9,10,11,12, and 13,14,15.
You could also make this into an extension method.
Try it online
If you mean why you are not getting groups of 6, the reason for this is that you are flooring the length of tags / 6. So, if the last group has the length of less that 6, it won't get added. Add this to the end:
if (tags.Length%6!=0) { string[] groupArrays = tags[i..tags.Length] } // You can do this manually.
As said before, it's because you use Math.Floor(). Use either Math.Ceiling or remove the -1 from i<= taglength - 1.
Array.Copy will still produce errors when you're tags aren't an exact multiple of 6.
Below code should do the trick and won't produce an error
string[] tags = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" };
int baselength = 6;
double tagLength = (int)Math.Floor(tags.Length / (double)6);
int length = baselength;
for (int i = 0; i <= tagLength; i++)
{
string[] groupArrays = new string[baselength];
if (i == tagLength)
length = ((i + 1) * length) - tags.Length;
if(length > 0 && length < baselength)
Array.Copy(tags, i * 6, groupArrays, 0, length);
}
Because you use Math.Floor(...). You should use Math.Ceiling(...) instead.
(int)Math.Floor(15d / 6d) // returns 2 >> 2 groups.
(int)Math.Ceiling(15d / 6d) // returns 3 >> 3 groups.
Beware though, you will get an ArgumentOutOfRangeException in Array.Copy, since index 3 * 6 does not exist. You will have to find a way around that.
One possible solution:
string[] tags = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" };
double tagLength = (int)Math.Ceiling(tags.Length / (double)6);
for (int i = 0; i <= tagLength - 1; i++)
{
int arrLength = (i + 1) * 6 <= tags.Length ? 6 : tags.Length % 6;
string[] groupArrays = new string[arrLength]; // or six if you always want a length of 6
Array.Copy(tags, i * 6, groupArrays, 0, arrLength);
}
Or using Linq:
for (int i = 0; i < (int)Math.Ceiling(tags.Length / 6d); i++)
{
string[] groupArrays = tags.Skip(i * 6).Take(6).ToArray();
}

How to combine values of several lists into one in C#?

I'm trying to merge several values of diffrent lists into one line.
for example:
list A = [1,2,3,4,5,6,7,8,9]
list B = [A,B,C,D]
list C = [!,?,-]
then ill go with a loop through all lists and the output should be:
line = [1,A,!]
line = [2,B,?]
line = [3,C,-]
line = [4,D,NULL]
line = [5,NULL, NULL]
line = [6 ,NULL ,NULL]...
The result will be added into one object
So far I tried to iterate through my lists with foreach loops but after I debugging it's clear that my approach cant work:
foreach (var item in list1){
foreach (var item2 in list2){
foreach (var item3 in list3){
string line = makeStringFrom(item, item2, item3);
}
}
}
But I dont know how to make it work.
You can also use LINQ functions.
var listA = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var listB = new List<string> { "A", "B", "C", "D" };
var listC = new List<string> { "!", "?", "-" };
var result = Enumerable.Range(0, Math.Max(Math.Max(listA.Count, listB.Count), listC.Count))
.Select(i => new
{
a = listA.ElementAtOrDefault(i),
b = listB.ElementAtOrDefault(i),
c = listC.ElementAtOrDefault(i)
}).ToList();
foreach (var item in result)
{
Console.WriteLine("{0} {1} {2}", item.a, item.b, item.c);
}
Result:
1 A !
2 B ?
3 C -
4 D
5
6
7
8
9
The general method would be:
Find the maximum length of all of the lists
Then create a loop to go from 0 to the max length-1
Check if each list contains that index of the item, and if so,
retrieve the value, otherwise return null
Build your line from those values
You can use this:
var A = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var B = new List<string>() { "A", "B", "C", "D" };
var C = new List<string>() { "!", "?", "-"};
var lists = new List<List<string>>() { A, B, C };
int count = 0;
foreach ( var list in lists )
count = Math.Max(count, list.Count);
var result = new List<List<string>>();
for ( int index = 0; index < count; index++ )
{
var item = new List<string>();
result.Add(item);
foreach ( var list in lists )
item.Add(index < list.Count ? list[index] : null);
}
foreach ( var list in result )
{
string str = "";
foreach ( var item in list )
str += ( item == null ? "(null)" : item ) + " ";
str.TrimEnd(' ');
Console.WriteLine(str);
}
We create a list of the lists so you can use that for any number of lists.
Next we take the max count of these lists.
Then we parse them as indicated by the algorithm:
We create a new list.
We add this list to the result that is a list of lists.
We add in this new list each of others lists items while taking null is no more items available.
You can use a StringBuilder if you plan to manage several and big lists to optimize memory strings concatenation.
Fiddle Snippet
Output
1 A !
2 B ?
3 C -
4 D (null)
5 (null) (null)
6 (null) (null)
7 (null) (null)
8 (null) (null)
9 (null) (null)

How to Group an array by lengths of 10, 0-10, 11-20, etc

I'm attempting to group an array of strings by their lengths, ie 1-10, 11-20, 21-30, then sort them using Linq/C#. I was thinking that I could loop through and do an if statement to break them up into separate arrays, then put them back together into one. This has a bad feel though - like Group By is a better option, but I haven't been able to figure out how exactly.
with helper range array, you can group list and then sort it
string[] list = new[] { "12345", "12", "12", "55", "12345", "1", "22", "333" };
var range = new[] { 2, 4, 5 };
var grouppedItems = list.GroupBy(s => range.First(i => i >= s.Length));
var sortedItems = grouppedItems.OrderBy(group => group.Key);
Some good ideas in the question's comments, Here I come with a solution where you would have a full control on each property while showing records on the view.
You can use desired length of interval you want, 10, 15, 20 whatever, also you will have min and max length in hand for each group to be used on view if you wanted to show the length range with each set.
string[] strings = new[] { "Taco Bell", "McDonalds", "Pizza Hut", "Wendys", "Dunkin' Donuts" };
int lengthRangeInterval = 10;
var groupsByLengthRange = strings.GroupBy(s => s.Length / lengthRangeInterval).Select(g =>
new
{
MinLength = (g.Key * lengthRangeInterval) + 1,
MaxLength = (g.Key * lengthRangeInterval) + lengthRangeInterval,
Items = g.ToArray()
}).OrderBy(g => g.MinLength).ToArray();
Not clear from the question exactly what you want to sort by. If you want to sort by the length, then here's a solution.
new[] { "nine char", "ten chars!", "13 characters", "14 characters!", "eight ch", "twentytwo!!!!!!!!!!!!!", "twentythree!!!!!!!!!!!!" }
.GroupBy( x => (x.Length - 1) / 10 )
.OrderBy(group => group.Key )
.Select( group => group.ToArray() );

C# How to calculate all 3 letter combinations with a certain value

I have 11 letters and they have values. The first have the same value as their numbering 1 to 10, but the eleventh has a value of 20. The question is how can I print out all 3 letter combinations with a total value of 23. Can you please help me I don’t even know where to start?
Let's first put your letters into a Dictionary<string, int> where Key is the letter, and Value is the value associated with each key.
var values = new Dictionary<string, int>
{
{ "A", 1 },
{ "B", 2 },
{ "C", 3 },
{ "D", 4 },
{ "E", 5 },
{ "F", 6 },
{ "G", 7 },
{ "H", 8 },
{ "I", 9 },
{ "J", 10 },
{ "K", 20 }
};
To get all 3 letter combos whose values add up to 23, first you need to get all 3 letter combos. So let's do that. The following function iterates through the dictionary and gets all 3 letter combos.
private static List<List<KeyValuePair<string, int>>> GetAll3LetterCombos(Dictionary<string, int> values)
{
var comboList = new List<List<KeyValuePair<string, int>>>();
for (int outer = 0; outer < values.Count; outer++)
{
for (int mid = outer + 1; mid < values.Count; mid++)
{
for (int inner = mid + 1; inner < values.Count; inner++)
{
var combo = new List<KeyValuePair<string, int>>
{
values.ElementAt(outer),
values.ElementAt(mid),
values.ElementAt(inner)
};
comboList.Add(combo);
}
}
}
return comboList;
}
Then, using LINQ, we can filter out that result where the sum of values in each KeyValuePair is equal to 23.
var threeLetterCombos = GetAll3LetterCombos(values);
var addsTo23 = threeLetterCombos.Where(x => x.Sum(y => y.Value) == 23).ToList();
The result:
[A 1] [B 2] [K 20]
[D 4] [I 9] [J 10]
[E 5] [H 8] [J 10]
[F 6] [G 7] [J 10]
[F 6] [H 8] [I 9]
One way to do this is a brute-force solution, where you compare every possible combination of three-letter values and store those that equal 23.
First, a simple class to represent a Letter, that has a Text property and a Value property:
public class Letter
{
public int Value { get; set; }
public char Text { get; set; }
public override string ToString()
{
return $"{Text} ({Value})";
}
}
Then, we can populate a list of these from A-K, where each letter has it's corresponding "index + 1" value except the last, which is 20:
var letters = Enumerable.Range(65, 10)
.Select(i => new Letter {Value = i - 64, Text = (char)i })
.ToList();
letters.Add(new Letter {Value = 20, Text = 'K'});
Then we can create a List<List<Letter>> object to hold the combinations that add up to 23:
var combos = new List<List<Letter>>();
And the brute-force solution is to simply use 3 loops to add a List<Letter> of the sum of each number with every combination of two numbers after it:
for (int first = 0; first < letters.Count; first++)
{
for (int second = first + 1; second < letters.Count; second++)
{
for (int third = second + 1; third < letters.Count; third++)
{
combos.Add(new List<Letter>
{letters[first], letters[second], letters[third]});
}
}
}
When this is done, we can filter and display the results of only those whose sum is 23:
// Output the combinations
Console.WriteLine("Here are the combinations that equal 23:\r\n");
foreach (var combo in combos.Where(c => c.Sum(l => l.Value) == 23))
{
Console.WriteLine(string.Join(" +\t", combo) +
$"\t= {combo.Sum(l => l.Value)}");
}
Output

Move existing item to the top of a listview

I add items from an array into a ListView like below:
for (int i = 0; i < dataKeyList.Count; i++)
{
CallTabLv.Items.Add(new { Label = " " + keyArray[i], Value = valueArray[i] });
}
If the keyArray[i] contains an item called CustomerName, how can I move it and its value to the top of the list ?
Edit:
Let say:
string[] arr1 = new string[] { "one", "two", "three" };
string[] arr2 = new string[] { "1", "2", "3" };
for (int i = 0; i < arr1.Length; i++)
{
listView.Items.Add(new { C1 = arr1[i], C2 = arr2[i] });
}
Output:
Col Col2
-----------
one 1
two 2
three 3
I want to move "three 3" to the top of the list, so it would be like:
Col Col2
-----------
three 3
two 2
one 1
Any suggestions?
Instead of adding item, You can use [Items.Insert][1] to insert an item in particular position,It can be used To Change position of an existing item in nth index.
ListViewItem item= new ListViewItem("Test");//Define item here;
if(!CallTabLv.Items.Contains(theItem))
{
CallTabLv.Items.Insert(0,item);
}
else
{
n = CallTabLv.Items.IndexOf(item);
CallTabLv.Items.RemoveAt(n);
CallTabLv.Items.Insert(0, item);
}

Categories

Resources