I have an array of strings. I need to sort the list and save each letter's item in a single line. After this, I need to find the longest line of string.
I have done the first part in an inefficient way but I am trying to make it concise.
List<string> fruits = new List<string>
{
"Pomme",
"Apple",
"Apricots",
"Avocado",
"Banana",
"Blackberries",
"Blackcurrant",
"Blueberries",
"Cherries",
"Clementine",
"Cranberries",
"Custard-Apple",
"Durian",
"Elderberries",
"Feijoa",
"Figs",
"Gooseberries",
"Grapefruit",
"Grapes",
"Guava",
"Breadfruit",
"Cantaloupe",
"Carambola",
"Cherimoya",
};
fruits.Sort();
List<string> sortedString = new List<string> { };
foreach (var str in fruits)
{
sortedString.Add(str);
}
//string A, B, C, D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S;
var A = "";
var B = "";
var C = "";
var D = "";
var E = "";
var F = "";
var G = "";
foreach (var item in sortedString)
{
if (item.StartsWith('A'))
{
A += item;
}
else if (item.StartsWith('B'))
{
B += item;
}
else if (item.StartsWith('C'))
{
C += item;
}
else if (item.StartsWith('D'))
{
D += item;
}
else if (item.StartsWith('E'))
{
E += item;
}
else if (item.StartsWith('F'))
{
F += item;
}
}
The result will be like -
AppleApricotsAvocado
BananaBlackberriesBlackcurrantBlueberriesBreadfruit
CantaloupeCarambolaCherimoyaCherriesClementineCranberriesCustard-Apple
Durian
Elderberries
FeijoaFigs
GooseberriesGrapefruitGrapesGuava
After this, I need to find the longest line and put space between each item. Without effective looping, the code will be messy. Can you assist me to show the right way to solve the problem?
The Sort() method already sorts your list and you don't need to assign it to a new one.
My proposal to resolve your problem is
fruits.Sort();
var result = fruits.GroupBy(f => f[0]);
int[] lineslength = new int[result.Count()];
int index = 0;
foreach (var group in result)
{
foreach (var item in group)
{
lineslength[index] += item.Length;
Console.Write(item + " ");
}
Console.WriteLine();
index++;
}
int longestIndex = Array.FindIndex(lineslength, val => val.Equals(lineslength.Max()));
Console.WriteLine(longestIndex);
I used the GroupBy method to group strings by their first letter. Then when I was displaying strings I also counted their length. Using the static FindIndex method of the Array class, I found the index containing the maximum value of the array what corresponds to the line with the maximum length. So index zero is the first line, one is the second line etc.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to get count the elements in an array but without linq
Example:
string a = "cat";
string b = "dog";
string c = "cat";
string d = "horse";
var list = new List<string>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);
And
desired result is : cat=2, dog=1, horse=1
Here's one way I could think of using a Dictionary<string, int>:
public static Dictionary<string, int> GetObjectCount(List<string> items)
{
// Dictionary object to return
Dictionary<string, int> keysAndCount = new Dictionary<string, int>();
// Iterate your string values
foreach(string s in items)
{
// Check if dictionary contains the key, if so, add to count
if (keysAndCount.ContainsKey(s))
{
keysAndCount[s]++;
}
else
{
// Add key to dictionary with initial count of 1
keysAndCount.Add(s, 1);
}
}
return keysAndCount;
}
Then get the result back and print to console:
Dictionary<string, int> dic = GetObjectCount(list);
//Print to Console
foreach(string s in dic.Keys)
{
Console.WriteLine(s + " has a count of: " + dic[s]);
}
I am not sure why are you looking for LINQ less solution for this as this could be done very easily and efficiently by it. I strongly suggest you to use it and do it like below :
var _group = list.GroupBy(i => i);
string result = "";
foreach (var grp in _group)
result += grp.Key + ": " + grp.Count() + Environment.NewLine;
MessageBox.Show(result);
Otherwise you can do it like below if you really unable to use LINQ :
Dictionary<string, int> listCount = new Dictionary<string, int>();
foreach (string item in list)
if (!listCount.ContainsKey(item))
listCount.Add(item, 1);
else
listCount[item]++;
string result2 = "";
foreach (KeyValuePair<string, int> item in listCount)
result2 += item.Key + ": " + item.Value + Environment.NewLine;
MessageBox.Show(result2);
The simple solution to your issue is a foreach loop.
string[] myStrings = new string[] { "Cat", "Dog", "Horse", "CaT", "cat", "DOG" };
Console.WriteLine($"There are {GetCount(myStrings, "cat");} cats.");
static int GetCount(string[] strings, string searchTerm) {
int result = 0;
foreach (string s in strings)
if (s == searchTerm)
result++;
return result;
}
Linq does this under the hood. However, unless this is either for optimization of large lists or for learning experience, Linq should be your preferred choice if you know how to use it. It exists to make your life easier.
Another implementation of this would be to simplify the number of calls you need and just write the output in the method:
string[] myStrings = new string[] { "Cat", "Dog", "Horse", "CaT", "cat", "DOG" };
CountTerms(myStrings, "cat", "dog");
Console.ReadKey();
static void CountTerms(string[] strings, params string[] terms) {
foreach (string term in terms) {
int result = 0;
foreach (string s in strings)
if (s == term)
result++;
Console.WriteLine($"There are {result} instances of {term}");
}
}
With that said, I heavily recommend Ryan Wilson's answer. His version simplifies the task at hand. The only downside to his implementation is if you are implementing this in a singular manner the way List<string>.Count(c => c == "cat") would.
You could try something like:
public int countOccurances(List<string> inputList, string countFor)
{
// Identifiers used are:
int countSoFar = 0;
// Go through your list to count
foreach (string listItem in inputList)
{
// Check your condition
if (listItem == countFor)
{
countSoFar++;
}
}
// Return the results
return countSoFar;
}
this will give you the count for any sting you give it. As always there is a better way but this is a good start.
Or if you want:
public string countOccurances(List<string> inputList, string countFor)
{
// Identifiers used are:
int countSoFar = 0;
string result = countFor;
// Go through your list to count
foreach (string listItem in inputList)
{
// Check your condition
if (listItem == countFor)
{
countSoFar++;
}
}
// Return the results
return countFor + " = " countSoFar;
}
Or an even better option:
private static void CountOccurances(List<string> inputList, string countFor)
{
int result = 0;
foreach (string s in inputList)
{
if (s == countFor)
{
result++;
}
}
Console.WriteLine($"There are {result} occurrances of {countFor}.");
}
Linq is supposed to make developer's life easy. Anyway you could make something like this:
string a = "cat";
string b = "dog";
string c = "cat";
string d = "horse";
var list = new List<string>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);
var result = GetCount(list);
Console.WriteLine(result);
Console.ReadLine();
static string GetCount(List<string> obj)
{
string result = string.Empty;
int cat = 0;
int dog = 0;
int horse = 0;
foreach (var item in obj)
{
switch (item)
{
case "dog":
dog++;
break;
case "cat":
cat++;
break;
case "horse":
horse++;
break;
}
}
result = "cat = " + cat.ToString() + " dog = " + dog.ToString() + " horse = " + horse.ToString();
return result;
}
I'm trying to automate the nested foreach provided that there is a Master List holding List of strings as items for the following scenario.
Here for example I have 5 list of strings held by a master list lstMaster
List<string> lst1 = new List<string> { "1", "2" };
List<string> lst2 = new List<string> { "-" };
List<string> lst3 = new List<string> { "Jan", "Feb" };
List<string> lst4 = new List<string> { "-" };
List<string> lst5 = new List<string> { "2014", "2015" };
List<List<string>> lstMaster = new List<List<string>> { lst1, lst2, lst3, lst4, lst5 };
List<string> lstRes = new List<string>();
foreach (var item1 in lst1)
{
foreach (var item2 in lst2)
{
foreach (var item3 in lst3)
{
foreach (var item4 in lst4)
{
foreach (var item5 in lst5)
{
lstRes.Add(item1 + item2 + item3 + item4 + item5);
}
}
}
}
}
I want to automate the below for loop regardless of the number of list items held by the master list lstMaster
Just do a cross-join with each successive list:
IEnumerable<string> lstRes = new List<string> {null};
foreach(var list in lstMaster)
{
// cross join the current result with each member of the next list
lstRes = lstRes.SelectMany(o => list.Select(s => o + s));
}
results:
List<String> (8 items)
------------------------
1-Jan-2014
1-Jan-2015
1-Feb-2014
1-Feb-2015
2-Jan-2014
2-Jan-2015
2-Feb-2014
2-Feb-2015
Notes:
Declaring lstRes as an IEnumerable<string> prevents the unnecessary creation of additional lists that will be thrown away
with each iteration
The instinctual null is used so that the first cross-join will have something to build on (with strings, null + s = s)
To make this truly dynamic you need two arrays of int loop variables (index and count):
int numLoops = lstMaster.Count;
int[] loopIndex = new int[numLoops];
int[] loopCnt = new int[numLoops];
Then you need the logic to iterate through all these loopIndexes.
Init to start value (optional)
for(int i = 0; i < numLoops; i++) loopIndex[i] = 0;
for(int i = 0; i < numLoops; i++) loopCnt[i] = lstMaster[i].Count;
Finally a big loop that works through all combinations.
bool finished = false;
while(!finished)
{
// access current element
string line = "";
for(int i = 0; i < numLoops; i++)
{
line += lstMaster[i][loopIndex[i]];
}
llstRes.Add(line);
int n = numLoops-1;
for(;;)
{
// increment innermost loop
loopIndex[n]++;
// if at Cnt: reset, increment outer loop
if(loopIndex[n] < loopCnt[n]) break;
loopIndex[n] = 0;
n--;
if(n < 0)
{
finished=true;
break;
}
}
}
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<IEnumerable<T>> lists)
{
IEnumerable<IEnumerable<T>> result = new List<IEnumerable<T>> { new List<T>() };
return lists.Aggregate(result, (current, list) => current.SelectMany(o => list.Select(s => o.Union(new[] { s }))));
}
var totalCombinations = 1;
foreach (var l in lstMaster)
{
totalCombinations *= l.Count == 0 ? 1 : l.Count;
}
var res = new string[totalCombinations];
for (int i = 0; i < lstMaster.Count; ++i)
{
var numOfEntries = totalCombinations / lstMaster[i].Count;
for (int j = 0; j < lstMaster[i].Count; ++j)
{
for (int k = numOfEntries * j; k < numOfEntries * (j + 1); ++k)
{
if (res[k] == null)
{
res[k] = lstMaster[i][j];
}
else
{
res[k] += lstMaster[i][j];
}
}
}
}
The algorithm starts from calculating how many combinations we need for all the sub lists.
When we know that we create a result array with exactly this number of entries. Then the algorithm iterates through all the sub lists, extract item from a sub list and calculates how many times the item should occur in the result and adds the item the specified number of times to the results. Moves to next item in the same list and adds to remaining fields (or as many as required if there is more than two items in the list). And it continues through all the sub lists and all the items.
One area though that needs improvement is when the list is empty. There is a risk of DivideByZeroException. I didn't add that. I'd prefer to focus on conveying the idea behind the calculations and didn't want to obfuscate it with additional checks.
I have a class WordCount which has string wordDic and int count. Next, I have a List.
I have ANOTHER List which has lots of words inside it. I am trying to use List to count the occurrences of each word inside List.
Below is where I am stuck.
class WordCount
{
string wordDic;
int count;
}
List<WordCount> usd = new List<WordCount>();
foreach (string word in wordsList)
{
if (usd.wordDic.Contains(new WordCount {wordDic=word, count=0 }))
usd.count[value] = usd.counts[value] + 1;
else
usd.Add(new WordCount() {wordDic=word, count=1});
}
I don't know how to properly implement this in code but I am trying to search my List to see if the word in wordsList already exists and if it does, add 1 to count but if it doesn't then insert it inside usd with count of 1.
Note: *I have to use Lists to do this. I am not allowed to use anything else like hash tables...*
This is the answer before you edited to only use lists...btw, what is driving that requirement?
List<string> words = new List<string> {...};
// For case-insensitive you can instantiate with
// new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
Dictionary<string, int> counts = new Dictionary<string, int>();
foreach (string word in words)
{
if (counts.ContainsKey(word))
{
counts[word] += 1;
}
else
{
counts[word] = 1;
}
}
If you can only use lists, Can you use List<KeyValuePair<string,int>> counts which is the same thing as a dictionary (although I'm not sure it would guarantee uniqueness). The solution would be very similar. If you can only use lists the following will work.
List<string> words = new List<string>{...};
List<string> foundWord = new List<string>();
List<int> countWord = new List<int>();
foreach (string word in words)
{
if (foundWord.Contains(word))
{
countWord[foundWord.IndexOf(word)] += 1;
}
else
{
foundWord.Add(word);
countWord.Add(1);
}
}
Using your WordCount class
List<string> words = new List<string>{...};
List<WordCount> foundWord = new List<WordCount>();
foreach (string word in words)
{
WordCount match = foundWord.SingleOrDefault(w => w.wordDic == word);
if (match!= null)
{
match.count += 1;
}
else
{
foundWord.Add(new WordCount { wordDic = word, count = 1 });
}
}
You can use Linq to do this.
static void Main(string[] args)
{
List<string> wordsList = new List<string>()
{
"Cat",
"Dog",
"Cat",
"Hat"
};
List<WordCount> usd = wordsList.GroupBy(x => x)
.Select(x => new WordCount() { wordDic = x.Key, count = x.Count() })
.ToList();
}
Use linq: Assuming your list of words :
string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "abacus","apple", "cheese" };
You can do:
var count =
from word in words
group word.ToUpper() by word.ToUpper() into g
where g.Count() > 0
select new { g.Key, Count = g.Count() };
(or in your case, select new WordCount()... it'll depend on how you have your constructor set up)...
the result will look like:
First, all of your class member is private, thus, they could not be accessed somewhere out of your class. Let's assume you're using them in WordCount class too.
Second, your count member is an int. Therefore, follow statement will not work:
usd.count[value] = usd.counts[value] + 1;
And I think you've made a mistype between counts and count.
To solve your problem, find the counter responding your word. If it exists, increase count value, otherwise, create the new one.
foreach (string word in wordsList) {
WordCount counter = usd.Find(c => c.wordDic == word);
if (counter != null) // Counter exists
counter.count++;
else
usd.Add(new WordCount() { wordDic=word, count = 1 }); // Create new one
}
You should use a Dictionary as its faster when using the "Contains" method.
Just replace your list with this
Dictionary usd = new Dictionary();
foreach (string word in wordsList)
{
if (usd.ContainsKey(word.ToLower()))
usd.count[word.ToLower()].count++;
else
usd.Add(word.ToLower(), new WordCount() {wordDic=word, count=1});
}
seriously need some guideline on string sorting methodology. Perhaps, if able to provide some sample code would be a great help. This is not a homework. I would need this sorting method for concurrently checking multiple channel names and feed the channel accordingly based on the sort name/string result.
Firstly I would have the string array pattern something like below:
string[] strList1 = new string[] {"TDC1ABF", "TDC1ABI", "TDC1ABO" };
string[] strList2 = new string[] {"TDC2ABF", "TDC2ABI", "TDC2ABO"};
string[] strList3 = new string[] {"TDC3ABF", "TDC3ABO","TDC3ABI"}; //2nd and 3rd element are swapped
I would like to received a string[] result like below:
//result1 = "TDC1ABF , TDC2ABF, TDC3ABF"
//result2 = "TDC1ABI , TDC2ABI, TDC3ABI"
//result3 = "TDC1ABO , TDC2ABO, TDC3ABO"
Ok, here is my idea of doing the sorting.
First, each of the strList sort keyword *ABF.
Then, put all the strings with *ABF into result array.
Finally do Order sort to have the string array align into TDC1ABF, TDC2ABF, TDC3ABF accordingly.
Do the same thing for the other string array inside a loop.
So, my problem is.. how to search *ABF within a string inside a string array?
static void Main()
{
var strList1 = new[] { "TDC1ABF", "TDC1ABI", "TDC1ABO" };
var strList2 = new[] { "TDC2ABF", "TDC2ABI", "TDC2ABO" };
var strList3 = new[] { "TDC3ABF", "TDC3ABO", "TDC3ABI" };
var allItems = strList1.Concat(strList2).Concat(strList3);
var abfItems = allItems.Where(item => item.ToUpper().EndsWith("ABF"))
.OrderBy(item => item);
var abiItems = allItems.Where(item => item.ToUpper().EndsWith("ABI"))
.OrderBy(item => item);
var aboItems = allItems.Where(item => item.ToUpper().EndsWith("ABO"))
.OrderBy(item => item);
}
If you do something like this then you can compare all the sums and arrange them in order. The lower sums are the ones closer to 1st and the higher are the ones that are farther down.
static void Main(string[] args)
{
string[] strList1 = new string[] { "TDC1ABF", "TDC1ABI", "TDC1ABO" };
string[] strList2 = new string[] { "TDC2ABF", "TDC2ABI", "TDC2ABO" };
string[] strList3 = new string[] { "TDC3ABF", "TDC3ABO", "TDC3ABI" };
arrange(strList1);
arrange(strList2);
arrange(strList3);
}
public static void arrange(string[] list)
{
Console.WriteLine("OUT OF ORDER");
foreach (string item in list)
{
Console.WriteLine(item);
}
Console.WriteLine();
for (int x = 0; x < list.Length - 1; x++)
{
char[] temp = list[x].ToCharArray();
char[] temp1 = list[x + 1].ToCharArray();
int sum = 0;
foreach (char letter in temp)
{
sum += (int)letter; //This adds the ASCII value of each char
}
int sum2 = 0;
foreach (char letter in temp1)
{
sum2 += (int)letter; //This adds the ASCII value of each char
}
if (sum > sum2)
{
string swap1 = list[x];
list[x] = list[x + 1];
list[x + 1] = swap1;
}
}
Console.WriteLine("IN ORDER");
foreach (string item in list)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.ReadLine();
}
If the arrays are guaranteed to have as many elements as there are arrays then you could sort the individual arrays first, dump the sorted arrays into an nxn array and then transpose the matrix.
I want to compute rank of element in an IEnumerable list and assign it to the member. But below code works only when called 1st time. 2nd time call starts from last rank value. So instead of output 012 and 012, I'm getting 012 and 345
class MyClass
{
public string Name { get; set; }
public int Rank { get; set; }
}
public void SecondTimeRankEvaluvate()
{
MyClass[] myArray = new MyClass[]
{
new MyClass() { Name = "Foo" },
new MyClass() { Name = "Bar" },
new MyClass() { Name = "Baz" }
};
int r = 0;
var first = myArray.Select(s => { s.Rank = r++; return s; });
foreach (var item in first)
{
Console.Write(item.Rank);
}
// Prints 012
Console.WriteLine("");
foreach (var item in first)
{
Console.Write(item.Rank);
}
// Prints 345
}
I understand that the variable r is being captured (closure) and reused when called 2nd time. I don't want that behavior. Is there any clean way to compute rank and assign it?
Also r variable (in actual code) isn't in the same scope where foreach loop is present. It is in a function which returns var first
var first = myArray.Select((s, i) => { s.Rank = i; return s; });
LINQ uses lazy evaluation and runs the Select part every time you use myArray.
You can force evaluation to happen only once by storing the result in a List.
Change
var first = myArray.Select(s => { s.Rank = r++; return s; });
to
var first = myArray.Select(s => { s.Rank = r++; return s; }).ToList();
Another way would be to join myArray with a new sequence using Zip every time, like this
var first = myArray.Zip(Enumerable.Range(0, int.MaxValue), (s, r) =>
{
s.Rank = r;
return s;
});
You shouldn't use LINQ if you're not querying the collection.
To update each item in an array, use a for loop:
for (int i = 0; i < myArray.Length; i++)
{
myArray[i].Rank = i;
}
To update each item in an enumerable, use a foreach loop:
int r = 0;
foreach (var item in myArray)
{
item.Rank = r++;
}