How to Convert var to string?
In my windowsphone application page, i want to convert this var DemoHeader to a string.
XDocument myData = XDocument.Load("aarti.xml");
var DemoHeader = from query in myData.Descendants("bookinfo")
select new HeaderT
{
Header = (string)query.Element("header")
};
ContentHeaderLine.Text = DemoHeader.ToString(); //LINE GIVING WRONG DATA
public class HeaderT
{
string header;
public string Header
{
get { return header; }
set { header = value; }
}
}
How can i convert var DemoHeader to a string?
First, var is not a type by itself, the type will be inferred from the value by the compiler. Your type is actually HeaderT and your query returns an IEnumerable<HeaderT> (so possibly multiple).
Presuming you want the first header:
HeaderT first = DemoHeader.First();
string firstHeader = first.Header();
or you want all returned separated by comma:
string allHeaders = String.Join(",", DemoHeader.Select(dh => dh.Header()));
If you want that ToString returns something meaningful(instead of name of the type), override it:
public class HeaderT
{
private string header;
public string Header
{
get { return header; }
set { header = value; }
}
public override string ToString()
{
return Header;
}
}
Override ToString() in HeaderT class could help. After that, you DemoHeader variable is a list of HeaderT not a single HeaderT.
Related
I need to show the data of a list according to the code entered, the problem is when i want to show the data that corresponds to it is shown system.collections.generic.list
var _respuesta saves the data the problem is only that dont show the number and his binary format
only show "system.collections.generic.list"
the valhex and valbin variable should be saved but it is saved "system.collections.generic.list" or "nameofmyprogram.Form1.Tex.Form"
this happen
Thi is my code
private void button1_Click(object sender, EventArgs e)
{
bool ValidarEPC = true;
string Respuesta = "";
string caracter;
int LargoEPC = 0;
string varEPC = txtEPC.Text;
List<HexBin> listHexBin = new List<HexBin>()
{
new HexBin() { ValHex="0",ValBin="0000"},
new HexBin() { ValHex="1",ValBin="0001"},
new HexBin() { ValHex="2",ValBin="0010"},
new HexBin() { ValHex="3",ValBin="0011"},
new HexBin() { ValHex="4",ValBin="0100"},
new HexBin() { ValHex="5",ValBin="0101"},
new HexBin() { ValHex="6",ValBin="0110"},
new HexBin() { ValHex="7",ValBin="0111"},
new HexBin() { ValHex="8",ValBin="1000"},
new HexBin() { ValHex="9",ValBin="1001"},
new HexBin() { ValHex="A",ValBin="1010"},
new HexBin() { ValHex="B",ValBin="1011"},
new HexBin() { ValHex="C",ValBin="1100"},
new HexBin() { ValHex="D",ValBin="1101"},
new HexBin() { ValHex="E",ValBin="1110"},
new HexBin() { ValHex="F",ValBin="1111"},
};
LargoEPC = varEPC.Length;
if(LargoEPC<=25)
{
Respuesta = "";
for (int i = 0; i <= LargoEPC; i++)
{
caracter = varEPC.Substring(i, 1);
//the data and its binary form are saved
var _respuesta = listHexBin.Where(ValHex => ValHex.ValHex == caracter);
//but now only show the error "system.collections.generic.list"
Respuesta= _respuesta.ToString();
MessageBox.Show(Respuesta);
}
}
else
{
ValidarEPC = false;
Respuesta = "EPC no valido";
}
string aBinario = "EPC no valido";
MessageBox.Show(LargoEPC.ToString());
lblResult.Text = varEPC.ToString();
lblResult.Refresh();
}
class HexBin
{
public string ValHex { get; set; }
public string ValBin { get; set; }
}
}
The Object class has a ToString() method. Every other class inherits from Object, so every class has a ToString() method.
But what does that method do? Here it is:
public virtual String ToString()
{
return GetType().ToString();
}
Unless a class overrides ToString() with some other implementation, it's just going to return the name of the type. A lot of classes override ToString(). For example, Date or Uri will return a string representation of the date or URI.
List<T> doesn't override it. And that's probably good. Imagine if the list had 300,000 items in it. The result would be a massive string you couldn't look at.
So if you want to see a string containing all the values in the list you'll have to write some code. There are a few ways to do that.
string Display(IEnumerable<HexBin> hexBins)
{
return string.Join(Environment.NewLine, hexBins.Select(h => $"Hex: {h.ValHex} Bin: {h.ValBin}"));
}
That's going to take a collection of HexBin, create a string from each of them, and join them all together with a return in between so that if you showed it in a console, each one would be on a new line. (I'm guessing at what you'd want it to look like.)
If you knew that you always wanted the string representation of HexBin to look a certain way you could override ToString() in that class:
class HexBin
{
public string ValHex { get; set; }
public string ValBin { get; set; }
public override string ToString()
{
return $"Hex {ValHex} Bin {ValBin}";
}
}
Now if you called ToString() on a HexBin you'd get your nice-looking string representation.
As an example - I wouldn't actually do this - you could create a class like this:
class HexBins : List<HexBin>
{
public override string ToString()
{
return string.Join(Environment.NewLine, this);
}
}
Now if you call ToString() on this list it will call ToString() on all the objects in the list and put them all in one big string.
That's just an example to show how we can override ToString(). In most real scenarios creating another class just for this would be pointless. We would just write methods to show something however we want. We might override ToString() for HexBin, but even then we don't know for sure that we'll want a string version of it to look the same everywhere.
The Where will return an enumerated
Try
var _respuesta = listHexBin.FirstOrDefault(ValHex => ValHex.ValHex == caracter);
var Name = "Resources.myjson.json";
var NameJSON = new System.IO.StreamReader(typeof(Strings).GetTypeInfo().Assembly.GetManifestResourceStream(Name)).ReadToEnd();
var ParsedBrandJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<TheInfo>(NameJSON);
await JsonCS.LoadJson(ParsedBrandJSON);
And on the page:
static public class TheInfoJSON
{
static public TheInfo Data { get; set; }
static public async Task LoadJson(Data JSON)
{
Data = JSON;
}
}
and
public class TheInfo
{
public List<TheName> TheName { get; set; } = new List<TheName>();
}
My json:
{
"TheInfo":[
{
"TheName": ["Martin", "Jonas", "Alex", "Oscar"]
}
]
}
When i now try to compare how can i see if my JSON contains a certain object and then store that as a single TheName? Is it possible to do it in the same cast?
var TheNameDataFromOtherPage = OtherPage.TheName; //Here i gather the name from another page that i will compare with the JSON
//Wrong syntax
bool DoTheyMatch = TheNameDataFromOtherPage == TheInfoJSON.Data.TheName.Contains("Alex");
This is now wrong syntax because i cant compare the value to a bool. How can i get out the data i find and then instead of having TheInfoJSON.Data.TheName.Contains("Alex"); as a bool, back to a single value of TheName containing "Alex" so I can create a bool out of the two values to see if the JSON has it or not.
I tried to add something along the lines like this after the contains(): as TheInfo.TheName but that isnt the correct syntax either.
bool DoTheyMatch = TheInfoJSON.Data.TheName.Contains(TheNameDataFromOtherPage);
Can someone give me an example of the best way to return multiple comments from an if statement?
protected string CheckFacility(int FacilityId)
{
var cfacility = new List<string>();
BuildingPresenter b = new BuildingPresenter();
FunctionalAreaPresenter f = new FunctionalAreaPresenter();
if (b.GetBuildings(FacilityId) != null)
{
cfacility.Add("There are Functional Areas associated with this facility. ");
}
if (f.GetFunctionalAreas(FacilityId) != null)
{
cfacility.Add("There are Functional Areas associated with this facility. ");
}
var cfacilitystring = string.Join(",", cfacility);
I'm getting these errors.
Error 3 The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments
Error 4 Argument 2: cannot convert from 'System.Collections.Generic.List' to 'string[]'
var shirtAttributes = new List<string>();
if (shirt.IsBlack)
{
shirtAttributes.Add("black");
}
if (shirt.IsLarge)
{
shirtAttributes.Add("large");
}
if (shirt.IsLongSleeve)
{
shirtAttributes.Add("long sleeve");
}
var shirtAttributesString = string.Join(",", shirtAttributes);
Output is something like: "black, long sleeve" or "black" or "large, long sleeve"
You have many ways to deal with that, you can create a class and override the ToString() method:
public class Shirt{
public Shirt(string color, string size, string sleeve)
{
Color =color;
Size=size;
Sleeve=sleeve;
}
public string Color {get;set;}
public string Size {get;set}
public string Sleeve {get;set}
public override string ToString(){
return string.Format("shirt is color :{0} , size :{1} and shleeve: {2}",Color,Size,Sleeve )
}
}
So when you run your program after initializing your class with values
Shirt myShirt = new Shirt("black","large","long");
if(myShirt.Color=="black"&& myShirt.Size=="large" && myShirt.Sleeve=="long")
{
return myShirt.ToString();
}
else{
return "no match";//or want you want
}
Hope it will help.
I have a public function that queries against a specific entity. I would like to replicate the function for any table I pass in but don't know how. Here is the working function I want to make dynamic:
public string MaxDepartment()
{
CPLinkEntities _context = new CPLinkEntities();
results = _context.LOG_Departments.Max(t => t.LastUpdated); // hard coded
string hex = BitConverter.ToString(results);
hex = hex.Replace("-", "");
return hex;
}
What I would really like to do here is pass in an entity to query against. All entities have a timestamp. Here is what I envision it would look like but doesn't work:
public string MaxDepartment(CPLinkEntities tableName)
{
var results = tableName.Max(t => t.LastUpdated);
string hex = BitConverter.ToString(results);
hex = hex.Replace("-", "");
return hex;
}
Calling the function from controller then would be:
CPLinkEntities context = new CPLinkEntities();
var tableName = context.LOG_Departments;
var maxDept = cf.MaxDepartment(tableName);
The easiest way to do it without changing any of your existing classes (if you can, see Oleksii's answer) is to manually create the expression tree and have it select the property you want.
public static string MaxDepartment<U>(IQueryable<U> table)
{
var parameter = Expression.Parameter(typeof(U));
var property = Expression.Property(parameter, "LastUpdated");
var lambada = Expression.Lambda<Func<U, byte[]>>(property, parameter);
var results = table.Max(lambada);
string hex = BitConverter.ToString(results);
hex = hex.Replace("-", "");
return hex;
}
You would call it via
using(CPLinkEntities _context = new CPLinkEntities()) //You forgot to dispose in your original example
{
var max = MaxDepartment(_context.LOG_Departments);
//Do whatever you want with max here.
}
This will fail at runtime if you try to pass in a table that does not have a LastUpdated property.
I think you should mark your entity with an interface like this:
public interface ILastUpdatable
{
byte[] LastUpdated {get;set;}
}
public partial class LOG_Departments : ILastUpdatable
{
}
and then make your method expecting an object of type that implements an interface like this:
public string MaxDepartment<TLastUpdatable>(IQueryable<TLastUpdatable> updatables)
where TLastUpdatable : class, ILastUpdatable
{
var results = updatables.Max(t => t.LastUpdated);
string hex = BitConverter.ToString(results);
hex = hex.Replace("-", "");
return hex;
}
UPDATE:
Also you would consider to use it as extension method:
public static class MaxUpdatableExtensions
{
public static string MaxDepartment<TLastUpdatable>(this IQueryable<TLastUpdatable> updatables)
where TLastUpdatable : class, ILastUpdatable
{
var results = updatables.Max(t => t.LastUpdated);
string hex = BitConverter.ToString(results);
hex = hex.Replace("-", "");
return hex;
}
}
and call it like this:
CPLinkEntities _context = new CPLinkEntities();
var results = _context.LOG_Departments.MaxDepartment();
I am using .Net 3.5 - I have a problem trying list box items to a text file. I am using this code:
if (lbselected.Items.Count != 0) {
string Path = Application.StartupPath + "\\ClientSelected_DCX.txt";
StreamWriter writer = new StreamWriter(Path);
int selectedDCXCount = System.Convert.ToInt32(lbselected.Items.Count);
int i = 0;
while (i != selectedDCXCount) {
string selectedDCXText = (string)(lbselected.Items[i]);
writer.WriteLine(selectedDCXText);
i++;
}
writer.Close();
writer.Dispose();
}
MessageBox.Show("Selected list has been saved", "Success", MessageBoxButtons.OK);
An error occurs for this line:
string selectedDCXText = (string)(lbselected.Items[i]);
The error is:
Unable to cast object of type 'SampleData' to type 'System.String'
please help me
Use string selectedDCXText = lbselected.Items[i].ToString();
You should override ToString method in class, which instances you want to write into file. Inside ToString method you should format correct output string:
class SampleData
{
public string Name
{
get;set;
}
public int Id
{
get;set;
}
public override string ToString()
{
return this.Name + this.Id;
}
}
And then use
string selectedDCXText = (string)(lbselected.Items[i].ToString());
Make sure that you have overridden the ToString method in your SampleData class like below:
public class SampleData
{
// This is just a sample property. you should replace it with your own properties.
public string Name { get; set; }
public override string ToString()
{
// concat all the properties you wish to return as the string representation of this object.
return Name;
}
}
Now instead of the following line,
string selectedDCXText = (string)(lbselected.Items[i]);
you should use:
string selectedDCXText = lbselected.Items[i].ToString();
Unless you have ToString method overridden in your class, the ToString method will only output class qualified name E.G. "Sample.SampleData"