Get an array of string from a jagged array [closed] - c#

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 6 years ago.
Improve this question
I have a jagged array that contains other 1d string arrays:
string[] first = {"one","two"};
string[] second = {"three","four"};
string[][] jagged = {first,second};
When I try to get the sub-arrays, they give a null value (I might be doing something wrong):
foreach (string[] arr in jagged[][]) {
// My stuff here
}
Did I do something wrong in the array initialization progress or do I have to convert the sub-arrays somehow?

Just the foreach part is wrong.
I have tested it like as follows:
string[] first = { "one", "two" };
string[] second = {"three","four"};
string[][] jagged = {first,second};
foreach (string[] arr in jagged)
{
Console.WriteLine(string.Join(",", arr));
}
Output:
one, two
three, four

It should be:
foreach (string[] arr in jagged)
{
// My stuff here
}
I pasted your code on my local environment and could iterate just fine.

If you use jagged[][] in your loop, then possibly you get a type conversion failed message:
Cannot convert type 'char' to 'string'.
Instead use jagged in your loop.
public class Program
{
public static void Main()
{
string[] first = {"one","two"};
string[] second = {"three","four"};
string[][] jagged = {first,second};
foreach (string[] arr in jagged)
{
//Your code
}
}
}

Related

Array returns System.Int32[]? [duplicate]

This question already has answers here:
System.Int32[] displaying instead of Array elements [duplicate]
(4 answers)
Closed 2 years ago.
When I make a function to return an array with the correct results.
Instead of giving me the correct results, I get as result System.Int32[].
Anyone an idea why this is?
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MultiplyByLength(new int[] {2,3,1,0}));
}
public static int[] MultiplyByLength(int[] arr)
{
return arr.Select(x => x * arr.Length).ToArray();
}
}
You need to format it some how. An array doesn't have a ToString() override that knows how you want to format your type (int[]) to a string, in such cases it just returns the type name (which is what you are seeing)
foreach(var item in MultiplyByLength(new int[] {2,3,1,0})
Console.WriteLine(item);
or
Console.WriteLine(string.Join(Environment.NewLine, MultiplyByLength(new int[] {2,3,1,0}));
or
Console.WriteLine(string.Join(",", MultiplyByLength(new int[] {2,3,1,0}));

Getting multiple strings of the same lenght from array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i need to take the longest line, or multiple if there is, out of string array of lines and write it out in console together with its posision in the array, i managed to find the longest one but im unable to find multiple strings. Can anyone help? (sorry if this is hard to understand).
One way you could do this is store the longest lines and their indexes in a dictionary. Start with a temporary variable to hold the longest line, and then walk through the array. As we find lines that are equal length, add them to our dictionary. If we find a longer line, set the dictionary to a new one, with just that line added to it, and continue.
For example:
public static void PrintLongestLinesAndIndexes(string[] input)
{
if (input == null)
{
Console.WriteLine("No data");
return;
}
var longestLine = string.Empty;
var longestLines = new Dictionary<int, string>();
for (int i = 0; i < input.Length; i++)
{
// If this line is longer, reset our variables
if (input[i].Length > longestLine.Length)
{
longestLine = input[i];
longestLines = new Dictionary<int, string> {{i, input[i]}};
}
// If it's the same length, add it to our dictionary
else if (input[i].Length == longestLine.Length)
{
longestLines.Add(i, input[i]);
}
}
foreach (var line in longestLines)
{
Console.WriteLine($"'{line.Value}' was found at index: {line.Key}");
}
}
Then we can use it like:
public static void Main(string[] args)
{
PrintLongestLinesAndIndexes(new[]
{
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"
});
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
Another way to do this would be to use Linq to select the items and their indexes, group them by the item's length, then order them by the length and select the first group:
public static void PrintLongestLinesAndIndexes(string[] input)
{
Console.WriteLine(string.Join(Environment.NewLine,
input.Select((item, index) => new {item, index})
.GroupBy(i => i.item.Length)
.OrderByDescending(i => i.Key)
.First()
.Select(line => $"'{line.item}' was found at index: {line.index}")));
}

Checking string value in a string using c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have following code in my project
var ReturnStr = Final_BOM.Tables[0].Rows[0]["NEW_BOM_IDS"].ToString();
the above line returns "12,13" but some times only "12"
var ReturnBOM = dsBOMDEfault.Tables[0].Rows[0]["Item_ID"].ToString();
the above line returns "14,15,13".
I want to check ReturnBOM values in ReturnStr
Can any one help how to check
You can use intersect:
Here a quick one-liner:
var results = ReturnStr.Split(',').Select(int.Parse)
.Intersect(ReturnBOM.Split(',').Select(int.Parse))
Demo:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var ReturnStr = "12,13";
var ReturnBOM = "14,15,13";
// Convert string to array with Split(',')
// if you dont want int just remove `.Select(int.Parse)`
var ReturnStrElements = ReturnStr.Split(',').Select(int.Parse);
var ReturnBOMElements = ReturnBOM.Split(',').Select(int.Parse);
// Keep only common elements
var results = ReturnStrElements.Intersect(ReturnBOMElements);
foreach(var item in results)
{
Console.WriteLine(item);
}
}
}
We use Split() to convert a string to an array where the delimiter is ','
[Optional] We use Select(int.Parse) to convert each element from string to int.
We use Intersect() to keep only common elements
Use LINQ.
using System.Linq;
The below code will give you an IEnumerable of String with the values you are looking for.
var inBoth = ReturnStr.Split(',').Intersect(ReturnBOM.Split(','))
You may then iterate through the values, cast them to Int32 or do whatever action you want.
If i understanded rights:
string[] returnBomVals = ReturnBom.Split(',');
string[] returnStrVals = ReturnStr.Split(',');
foreach (var vals in returnStrVals)
{
foreach (var strVals in returnBomVals)
{
if (ReturnStr.Equals(vals))
{
//Do Actions
}
}
}

text if a string has a word in it and display that string if it does in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i want to have something like an "if" statement that tests a string for a word or a group of words.if the word(s) are in the string it displays the string on the console.
if anyone can help it would be much appreciated.
Though this is a terribly asked question; I'm going to go against my instincts and answer it.
Build a List<string> you want to search for:
private List<string> _words = new List<string> { "abc", "def", "ghi" };
then build a nice little extension method like this:
public static bool ContainsWords(this string s)
{
return _words.Any(w => s.Contains(w));
}
and so now you can just say:
myString.ContainsWords();
The entire extension class might look like this:
public static class Extensions
{
private List<string> _words = new List<string> { "abc", "def", "ghi" };
public static bool ContainsWords(this string s)
{
return _words.Any(w => s.Contains(w));
}
public static bool ContainsWords(this string s, List<string> words)
{
return words.Any(w => s.Contains(w));
}
}
NOTE: depending on the needs in your application, the second method is a lot more generic. It doesn't grab the list from the extensions class, but rather allows it to be injected. However, it could be that your application is so specific that the first approach is more appropriate.
Why not just use the .Contains() method....
string s = "i am a string!";
bool matched = s.Contains("am");
String [] words={"word1","word2","word3"};
String key="word2";
for(int i=0;i<words.Length;i++)
{
if(words[i].Contains(key))
Console.WriteLine(words[i]);
}
You can use String.Contains method like;
string s = "helloHellohi";
string[] array = new string[] { "hello", "Hello", "hi", "Hi", "hey", "Hey", "Hay", "hey" };
foreach (var item in array)
{
if(s.Contains(item))
Console.WriteLine(item);
}
Output will be;
hello
Hello
hi
Here a demonstration.

Any utility to print out array directly? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array, I am wondering any utility to print out array directly?
You can use string's Join() method, like this:
Console.WriteLine("My array: {0}",
string.Join(", ", myArray.Select(v => v.ToString()))
);
This will print array elements converted to string, separated by ", ".
You can use the following one liner to print an array
int[] array = new int[] { 1 , 2 , 3 , 4 };
Array.ForEach( array , x => Console.WriteLine(x) );
I like #dasblinkenlight solution, but I'd like to note that the select statement is not nessasary.
This code produces the same result for an array of strings:
string[] myArray = {"String 1", "String 2", "More strings"};
Console.WriteLine("My array: {0}", string.Join(", ", myArray));
I find it a little easier on the eyes having less code to read.
(linqpad is a fantastic app to test snippets of code like this.)
You can write an extension method something like this
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
var items = new []{ 1, 2, 3, 4, 5 };
items.PrintArray();
}
}
static class ArrayExtensions
{
public static void PrintArray<T>(this IEnumerable<T> elements)
{
foreach (var element in elements)
{
Console.WriteLine(element);
}
}
}
}

Categories

Resources