How to get PropertyInfo of C# object [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 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();
}
}

Related

How to add a string to a List [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 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);
}
}

Try to convert text file to Excel [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 4 years ago.
Improve this question
I have text file like this:
VehicleReferenceKey:2365565656
DriverReferenceKey:965454545454
Latitude:30000
**
VehicleReferenceKey:96896A4607A6
DriverReferenceKey:96896A4607A6
Latitude:500
**
VehicleReferenceKey:822F5B18
DriverReferenceKey:822F5B18
Latitude:1000
I try To convert this text file to Excel
first i made an Class as
public class Item
{
public string VehicleReferenceKey;
public string DriverReferenceKey;
public string Latitude;
}
then i read all text file and looping of it as
var lines = File.ReadAllLines(fileName);
for (var i = 0; i < lines.Length; i += 1) {
var line = lines[i];
// Process line
}
but I Can't determine how i can specify the Key and value
for each line , and how tell the sign
**
as it's breaker between each object .Any Help
Try following code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication87
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
Item items = new Item(FILENAME);
}
}
public class Item
{
public static List<Item> items = new List<Item>();
public string VehicleReferenceKey;
public string DriverReferenceKey;
public string Latitude;
public Item() { }
public Item(string filenam)
{
StreamReader reader = new StreamReader(filenam);
string line = "";
Item newItem = null;
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (line.Length > 0)
{
string[] rowItems = line.Split(new char[] { ':' });
switch (rowItems[0])
{
case "VehicleReferenceKey" :
newItem = new Item();
items.Add(newItem);
newItem.VehicleReferenceKey = rowItems[1];
break;
case "DriverReferenceKey":
newItem.DriverReferenceKey = rowItems[1];
break;
case "Latitude":
newItem.Latitude = rowItems[1];
break;
}
}
}
}
}
}
Basically it seems the following hold for your file:
The first item takes 3 lines (one for each field)
Every item after the first takes 7 lines (2 empty lines, 1 line containing "**", 1 empty line and then the 3 lines with the field values)
So there's no reason to parse the ** and the empty lines you can just skip those (by looping over 7 lines at a time).
For the seperating key and value you can use the String.Split method.
All in all it would look something like this:
for (var i = 0; i < lines.Length + 2; i += 7)
{
var newItem = new Item(){
VehicleReferenceKey = lines[i].Split(':')[1],
DriverReferenceKey = lines[i+1].Split(':')[1],
Latitude = lines[i+2].Split(':')[1]
}
//do whatever you want with the newItem
}

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.

Replacing ### with integers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
By using RegEx, or String.Replace, I need to replace any number of consecutive #'s (with the appropriate number of leading 0's) with an integer. I know I can search for # in the string, get the First and Last index, Last-First for the length, then replace with String.Replace. I was hoping someone would have a faster, and more slick answer.
Method header would be:
string ReplaceHashtagsWithInt(string input, int integer)
Examples:
Input -> "String####_Hi##", 2
Output -> "String0002_Hi02"
Input -> "String####_Hi##", 123
Output -> "String0123_Hi123"
public static class Testing
{
public static void Main()
{
ReplaceHashtagsWithInt("String####_Hi##", 2);
ReplaceHashtagsWithInt("String####_Hi###", 123);
ReplaceHashtagsWithInt("String####_Hi#######", 123);
}
public static string ReplaceHashtagsWithInt(string input, int integer)
{
Regex regex = new Regex("#+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value).ToArray();
Array.Sort(matches);
Array.Reverse(matches);
foreach (string match in matches)
{
Regex r = new Regex(match);
string zeroes = new string('0', match.Length - integer.ToString().Length) + integer;
input = r.Replace(input, zeroes);
}
return input;
}
}
You can do something like this:
using System;
using System.Text;
using System.Text.RegularExpressions;
public static class Testing
{
public static void Main()
{
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 1));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 23));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 456));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 7890));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 78901));
}
public static string ReplaceHashtagsWithInt(string input, int integer)
{
Regex regex = new Regex("#+");
StringBuilder output = new StringBuilder(input);
int allig = 0;
for(Match match = regex.Match(input);match.Success;match = match.NextMatch())
{
string num = integer.ToString();
if(num.Length<=match.Length)
for(int i=0;i<match.Length;i++)
{
if(i<match.Length-num.Length)
output[match.Index+i+allig] = '0';
else
output[match.Index+i+allig] = num[i-match.Length+num.Length];
}
else
{
output.Remove(match.Index+allig,match.Length);
output.Insert(match.Index+allig,num);
allig+=num.Length-match.Length;
}
}
return output.ToString();
}
}

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