How to add a string to a List [closed] - c#

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 months ago.
Improve this question
I have a variable usersInput which has a value Console.ReadLine()
I want to add this variable to the array built with List
static void Resize<T>(ref List<T> array, string name)
{
array.Add(name);
Console.WriteLine();
for (int i = 0; i < array.Count; i++)
{
Console.WriteLine(array[i]);
}
}
static void Main(string[] args)
{
List<string> teachers = new List<string> { "1", "2", "3"};
Console.WriteLine("Enter a name");
string userInput = Console.ReadLine();
Resize(ref teachers, userInput);
}

Why do you need Resize<T> method at all? You could do it easier:
static void Main(string[] args)
{
List<string> teachers = new List<string> { "1", "2", "3" };
Console.WriteLine("Enter a name");
string userInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(userInput) || !string.IsNullOrEmpty(userInput))
{
teachers.Add(userInput);
}
// if want to change list to array then use
// var arr = teachers.ToArray();
foreach (var teacher in teachers)
{
Console.WriteLine(teacher);
}
}

Related

Assigning values to objects in a foreach loop [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
How to assign values to objects in foreach loop.
Code is below:
using System;
namespace WorkingWithClasses
{
class Program
{
static void Main(string[] args)
{
//create 5 player objects
Player[] players = new Player[5];
//assigning a value to a player brings null reference exception error:
foreach(Player player in players)
{
player.Skill = 5;
}
float skillSum = 0;
foreach(Player player in players)
{
skillSum += player.Skill;
}
Console.WriteLine(skillSum);
}
}
class Player
{
public float Skill { get; set; }
}
}
Every "Player" in your players array is not initialized. Try with this for loop instead of the foreach loop where you are getting the null reference:
for (var i = 0; i < players.Length; i++)
{
players[i] = new Player() { Skill = 5 };
}
You can also use this, however it's slower than iterating through the array with a for loop:
using System.Linq;
players = Enumerable.Repeat(new Player() { Skill = 5 }, 5).ToArray();
You need to initialize your players instance object since you are creating array holder.
Replace Player[] players = new Player[5]; with
Player[] players = Enumerable.Repeat(new Player(), 5).ToArray();

What to return if condition is not satisifed? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The method looks as following:
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
var result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
return result;
}
}
It's obvious that not all paths return something and the issue is I can't return null.
How to rearrange the method?
Maybe you can initialize your List?
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
List<string> result = new List<string>()
{
owner,
string.Empty,
string.Empty
};
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
}
return result;
}
I usually do this when I want to create an assembler method for example to tranform a List<X> to another List<Y>, so if my List<X> is null I try to return an empty List of Y. I prefer to do this instead of throwing exceptions and getting my Dashboard full of errors. But It depends on how your codes works.

How to parse this following string? [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 6 years ago.
Improve this question
I have to parse this string
"Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing"
as Code, Description like Code=Cust and Description=Customer
split on basis of space is not working for this because there is also a space in description too .
Instead of splitting on space you can split on the equals sign. Then the code will be the value after the last space of the previous item and the description will be everything up to the last space making sure to trim the spaces that might show up before the equals. And you can replace the Dictionary with whatever data type you want to load the values into. Also you have to handle the first and last values as special cases. Note this will only work if the codes do not contain spaces.
string str = "Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing";
var separated = str.Split('=');
string code = separated[0].Trim();
var codeAndDescription = new Dictionary<string, string>();
for (int i = 1; i < separated.Length - 1; i++)
{
int lastSpace = separated[i].Trim().LastIndexOf(' ');
var description = separated[i].Substring(0, lastSpace).Trim();
codeAndDescription.Add(code, description);
code = separated[i].Substring(lastSpace + 1).Trim();
}
codeAndDescription.Add(code, separated[separated.Length - 1]);
foreach (var kvp in codeAndDescription)
Console.WriteLine(kvp);
Outputs
[Cust, Customer]
[CustCR, Customer Credit]
[Prod, Product]
[SalesRep, Sales Rep]
[TaxCat, Tax Category]
[TaxId, Tax ID]
[VolBill, Volume Billing]
A little modification for another case if description is empty, also used custom Item class to store output in a list
class Item {
public string Code { get; set; }
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
string str = "0= 1=Full Time 2=Part Time 3=Seasonal 4=Variable";
var separated = str.Split('=');
string code = separated[0].Trim();
var codeAndDescription = new List<Item>();
foreach (var sep in separated.Skip(1).Take(separated.Length - 2))
{
int lastSpace = sep.Trim().LastIndexOf(' ');
var description = lastSpace != -1 ? sep.Substring(0, lastSpace).Trim(): "" ;
codeAndDescription.Add(new Item { Code=code,Description=description });
code = sep.Substring(lastSpace + 1).Trim();
}
codeAndDescription.Add(new Item { Code = code, Description = separated.Last() });
foreach (var kvp in codeAndDescription)
{
Console.WriteLine("Code={0} Description={1}", kvp.Code, kvp.Description);
}
Console.ReadLine();
}
}

How to get PropertyInfo of C# object [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 7 years ago.
Improve this question
I am trying to extract the PropertyInfo of an object but the propertyInfo returns no properties:
[TestMethod]
public void TestGetValueMethod()
{
var value = 23;
System.Reflection.PropertyInfo[] propertyInfo = value.GetType ().GetProperties();
//DTOPropertyInfo info = new DTOPropertyInfo(propertyInfo[0]);
System.Diagnostics.Debug.WriteLine(propertyInfo.Length);
}
propertyInfo.Length returns 0. What am I missing?
using System;
using System.Reflection;
class Example
{
public static void Main()
{
string test = "abcdefghijklmnopqrstuvwxyz";
// Get a PropertyInfo object representing the Chars property.
PropertyInfo pinfo = typeof(string).GetProperty("Chars");
// Show the first, seventh, and last letters
ShowIndividualCharacters(pinfo, test, 0, 6, test.Length - 1);
// Show the complete string.
Console.Write("The entire string: ");
for (int x = 0; x < test.Length; x++)
{
Console.Write(pinfo.GetValue(test, new Object[] {x}));
}
Console.WriteLine();
}
static void ShowIndividualCharacters(PropertyInfo pinfo,
object value,
params int[] indexes)
{
foreach (var index in indexes)
Console.WriteLine("Character in position {0,2}: '{1}'",
index, pinfo.GetValue(value, new object[] { index }));
Console.WriteLine();
}
}

Regex expression substring wildcard [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
In C# I'm trying to search for the substring "flight%sin" where %s would be a string. How would I do this using regex in c#?
You can capture the text between "flight" and "in" using #"flight(\w+)in"
The reference guide provides more detail.
Here is a Regex example in C#.
string [] mystrings = new string [] {"flight%sin", "flightTest1sin", "flighNoGoodsin", "flightTest2sin"};
foreach (string s in mystrings)
{
var groups = Regex.Match(s, #"flight(\w+)in");
if (groups.Groups.Count > 1)
{
Console.WriteLine(groups.Groups[1]);
}
}
Console.ReadKey();
Does this help?
string data = "flight 4057 in"; //I am guessing, this is what the original string will be.
public string getFlightNumber(string data)
{
int flightNumLength = 4;// Or however long the string would be
for(int index = 0; index < data.length(); index++)
{
if(index+flightNumLength + index < data.length())
{
string TempFlight = data.subSting(index, flightNumLength);
if(isNumeric(TempFlight))
{
return TempFlight;
}
}
}
}
public static bool IsNumeric(object Expression){
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
return isNum;
}

Categories