I've defined List
private class Kamery
{
public int iIndeks;
public string strNazwa;
public Kamery(int Indeks, string Nazwa)
{
iIndeks = Indeks;
strNazwa = Nazwa;
}
}
List<Kamery> lKamery = new List<Kamery>();
I'd like to cast searched list of names to string array like:
string[] strNazwa = (string)lKamery.Find(item => item.iIndeks == iIndeks).strNazwa.ToArray();
But compiler says Cannot convert type 'char[]' to 'string'
Why? How it needs to be done?
I think you want:
string[] strNazwa = lKamery.Where(item => item.iIndeks == iIndeks)
.Select(item => item.strNazwa)
.ToArray();
That will give you a string array that contains each of the strNazwa values from the list for items that meet the Where condition.
Here's what your original code was doing:
string[] strNazwa = (string)
// get the one item that matches the condition
lKamery.Find(item => item.iIndeks ==Indeks)
// get the strNazwa property from that one item
.strNazwa
// return the string as a char array
.ToArray();
When you try to cast the char[] to a string it fails since you can't cast it. You can create a string from a character array but not via a cast.
I think your problem is that .Find returns only 1 value , the first match in the list.
https://msdn.microsoft.com/en-us/library/x0b5b5bc(v=vs.110).aspx
This value will be a string and by using .toArray , you are converting that string to a char[ ] and then trying to cast it back to string.
I'm not that good at c# , so the generic solution would be:
Declare the array, do a foreach and every time the id matches put the name into the array and inc the index. This limits it somewhat as you have to have a fixed size, would probably be better to use List instead.
Related
Hi I am new to programming. I would like to read a text file and take the values ( strings ) and store each character of the string in an array individually. I have used a list to take in the vales from the text file. I am finding it difficult to move them into an array and then use those values in my program. Please find me a solution if possible. Thanking you in advance.
public class file_IO
{
string[] letters = new string[] //I would like to store it in this variable
public void File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
foreach (string line in file_lines)
{
}
}
}
Hope this will work for you!.
public char[] File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
StreamReader sr = new StreamReader(filepath);
string fileContentInString = sr.ReadToEnd();
sr.Close();
return fileContentInString.ToCharArray();
}
List<List<char>> linesAsChars = File.ReadAllLines(filepath)
.Select(l => l.ToList())
.ToList();
This will get a List of List of chars.
string implements IEnumerable<char>, so with ToList each line in the file is translated to List<char>.
Solution to "store each character of the string in an array individually" is fairly easy because string is in fact an array of char. You can do this using something like this :
char[] letters;
public void File_Reader()
{
string filepath = #"env.txt";
letters = File.ReadAllText(filePath).ToArray();
}
I'm not really sure if I have understood your question properly, but from what I have read, I will assume that you want an array of lines (which are strings).
In this case, you don't need to do much as the File.ReadAllLines() method naturally outputs an array of string variables.
Remove the for loop and replace
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
with:
letters = File.ReadAllLines(filepath)
In case what you want is actually an array of every char value in your file, I would refer to #m.rogalski's answer and declare an array of char[], for example, declare:
char[] fileChars;
and then replace the line I mentioned earlier with:
fileChars = readAllText(filePath).toCharArray()
You will notice that you do not need a loop in either of the above situations. Hope I helped.
I have an array of string and I want to get back from it a filtered array that contains only those strings that match the searched string.
string[] myValues = {"School.Report1", "School.Report2", "School.Report3", "House.Report1", "House.Report2"};
string myFilter = "School";
string[] filteredValues = myValues.Filter(myFilter); // or something similar
filteredValues must contains only: "School.Report1", "School.Report2", "School.Report3".
-- EDIT --
I prefer a non-LINQ approach if possibile. Otherwise I know that this question can be answered with the solution proposed here: filter an array in C#.
If you can't use LINQ you can still use Array.FindAll:
string[] filteredValues = Array.FindAll(myValues, s => s.Contains(myFilter));
or maybe you want to keep only all strings which first token(separated by dot) is School:
string[] filteredValues = Array.FindAll(myValues, s => s.Split('.')[0] == myFilter);
One possible answer is to make an IComparer that sorts the array by the matching value (if it contains filter return 1 else return 0) then find the first item outside the filter and make another array with the values up the one before that point.
I must doing something wrong... But I can't figure it out!
I have an array with string in it. I'm trying to fins if the Array contains some words like Sales for example.
drillDownUniqueNameArray[0] = "[Sales Territory].[Sales Territories].[Sales Territory Group].&[North America]";//Inside the string array there is this string in index 0
drillDownUniqueNameArray.Contains("S")//Output false!
Array.IndexOf(drillDownUniqueNameArray,"S")//Output -1! <--Fixed My answer
drillDownUniqueNameArray.Contains("[Sales Territory].[Sales Territories].[Sales Territory Group].&[North America]") //Output true!
I thouhgt Contains should find even part of the string..
How can I find if this array have "S" or "Sales" for example?
You are asking if the array contains a string that exactly matches "S".
What you want is to ask if any of the strings in the array contains the character "S", something like:
drillDownUniqueNameArray.Any(v => v.Contains("S"))
You're checking if the array contains an element that's exactly "S" but I think you are trying to check whether the array contains an alement that contains an "S".
You could achieve this by the following statement:
drillDownUniqueNameArray.Any( str => str.Contains ("S") )
You can try this.
drillDownUniqueNameArray[0].Contains("s");
You can use LINQ:
var allWithSales = drillDownUniqueNameArray
.Where(str => str.Contains("Sales"));
ignoring the case:
var allWithSalesIgnoreCase = drillDownUniqueNameArray
.Where(str => str.IndexOf("sales", StringComparison.OrdinalIgnoreCase) >= 0);
If you want to find all that contain a word "Sales"(String.Split() = white-space delimiter)):
var allWordsWithSales = drillDownUniqueNameArray
.Where(str => str.Split().Contains("Sales", StringComparer.OrdinalIgnoreCase));
Now you can enumerate the query with foreach or use ToArray() or ToList to create a collection:
foreach(string str in allWithSales)
Console.WriteLine(str);
You are finding it in the array, but you should find the word in the string.
Use following if you want to check:
drillDownUniqueNameArray.Any(x=>x.Contains("Sales"));
Use following if want to get the strings which contains "Sales"
drillDownUniqueNameArray.Where(x=>x.Contains("Sales"));
When you do it like this:
drillDownUniqueNameArray.Contains("S")
it's not gonna check the values, you must do it like this:
drillDownUniqueNameArray[0].Contains("S") or drillDownUniqueNameArray.First().Contains("S")
like this way it checks the values inside the array not the arrays itself
I have a method that takes an ArrayList object as a parameter.
I then try to convert this arrayList into a string array but get an InvalidCastException.
The ArrayList contains a seven random numbers. As they are of the type object I am assuming it shouldnt be a problem casting it into a string.
This is the method that I have called
p.matches(winningNumber);
public void matches(ArrayList al)
{
try
{
string nameFile;
string[] winningNumber = (string[])al.ToArray(typeof(string));
Console.WriteLine("Please enter the name of the file you want to Read from");
nameFile = Console.ReadLine();
it is with the attemt at casting that I get an exception.
You are getting this exception because in order to convert to array of strings, the elements themselves must be strings as well. You can do it with LINQ, though:
string[] winningNumber = al.Cast<object>().Select(o => o.ToString()).ToArray();
To deal with nulls, replace o.ToString() with ""+o or a conditional that checks for nulls.
You just need to use Enumerable.Cast before you call ToArray
string[] winningNumber = al.Cast<string>().ToArray();
Change
string[] winningNumber = (string[])al.ToArray(typeof(string));
To
string[] winningNumber = al.Cast<object>.Select(x=> x==null ? string.Empty : x.ToString()).ToArray();
If you have some items that are not string, you can use Enumerable.OfType. It will ignore non string types.
string[] winningNumber = al.OfType<string>().ToArray();
string[] winningNumber = al.Cast<object>.Select(x=>Convert.ToString(x)).ToArray();
I am trying to sort my arraylist.
The array list consists of data in time format.
Array:
9:15 AM, 10:20 AM
How should I sort it?
The result i get from below code is :
10:20 AM
9:15 AM
Below is my code:
String timeText = readFileTime.ReadLine();
timeSplit = timeText.Split(new char[] { '^' });
Array.Sort(timeSplit);
foreach (var sortedArray in timeSplit)
{
sortedTimeListBox.Items.Add(sortedArray);
}
Yes, since you simply split a string, you're merely sorting an array of strings (meaning 1 comes before 9 and it doesn't care about the decimal point). To get the sorting you desire, you need to first convert it into a DateTime like this:
timeSplit = timeText
.Split(new char[] { '^' });
.Select(x => new { Time = DateTime.Parse(x), String = x })
.OrderBy(x => x.Time)
.Select(x => x.String)
.ToArray();
Here, what we've done is:
Split the string as you had done before
Create a new anonymous type that contains the original string and also that string converted into a DateTime.
Ordered it by the DateTime property
Select'ed back to the original string
Converted it into an array
timeSplit now contains the strings sorted as you wanted.
Array.Sort(timeSplit, delegate(string first, string second)
{
return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
});