How to: Convert a string to an int (C# Programming Guide)
These examples show some different ways you can convert a string to an int. Such a conversion can be useful when obtaining numerical input from a command line argument, for example. Similar methods exist for converting strings to other numeric types, such as float or long. The table below lists some of those methods.
Numeric Type | Method |
---|---|
decimal | ToDecimal(String) |
float | ToSingle(String) |
double | ToDouble(String) |
short | ToInt16(String) |
int | ToInt32(String) |
long | ToInt64(String) |
ushort | ToUInt16(String) |
uint | ToUInt32(String) |
ulong | ToUInt64(String) |
This example calls the ToInt32(String) method to convert an input string to an int . The program catches the two most common exceptions that can be thrown by this method, FormatException and OverflowException. If the number can be incremented without overflowing the integer storage location, the program adds 1 to the result and prints the output.
static void Main(string[] args) { int numVal = -1; bool repeat = true; while (repeat == true) { Console.WriteLine("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive)."); string input = Console.ReadLine(); // ToInt32 can throw FormatException or OverflowException. try { numVal = Convert.ToInt32(input); } catch (FormatException e) { Console.WriteLine("Input string is not a sequence of digits."); } catch (OverflowException e) { Console.WriteLine("The number cannot fit in an Int32."); } finally { if (numVal < Int32.MaxValue) { Console.WriteLine("The new value is {0}", numVal + 1); } else { Console.WriteLine("numVal cannot be incremented beyond its current value"); } } Console.WriteLine("Go again? Y/N"); string go = Console.ReadLine(); if (go == "Y" || go == "y") { repeat = true; } else { repeat = false; } } // Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } // Sample Output: // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive). // 473 // The new value is 474 // Go again? Y/N // y // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive). // 2147483647 // numVal cannot be incremented beyond its current value // Go again? Y/N // Y // Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive). // -1000 // The new value is -999 // Go again? Y/N // n // Press any key to exit.
int numVal = Int32.Parse("-105"); Console.WriteLine(numVal); // Output: -105
// TryParse returns true if the conversion succeeded // and stores the result in the specified variable. int j; bool result = Int32.TryParse("-105", out j); if (true == result) Console.WriteLine(j); else Console.WriteLine("String could not be parsed."); // Output: -105
try { int m = Int32.Parse("abc"); } catch (FormatException e) { Console.WriteLine(e.Message); } // Output: Input string was not in a correct format.
string inputString = "abc"; int numValue; bool parsed = Int32.TryParse(inputString, out numValue); if (!parsed) Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString); // Output: Int32.TryParse could not parse 'abc' to an int.
LINQ to Datatable
private static DataTable JoinDataTablesWithLinq() { var query = from inv in _tblInvoice.AsEnumerable() join item in _tblLineItem.AsEnumerable() on inv["InvoiceId"] equals item["InvoiceId"] select new { CustomerName = inv["CustomerName"], ItemName = item["ItemName"], Quantity = item["Quantity"] }; return query.CopyToDataTable(); }
LINQ TO DATATABLE EXAMPLE:
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{ DataTable dtReturn = new DataTable();
// column names PropertyInfo[] oProps = null;
{ DataTable dtReturn = new DataTable();
// column names PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn; foreach (T rec in varlist)
{ // Use reflection to get property names, to create table, Only first time, others
will follow if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties(); foreach (PropertyInfo pi in oProps)
{ Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() ==typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
} DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue (rec,null);
}
dtReturn.Rows.Add(dr);
} return dtReturn;
}
{ // Use reflection to get property names, to create table, Only first time, others
will follow if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties(); foreach (PropertyInfo pi in oProps)
{ Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() ==typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
} DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue (rec,null);
}
dtReturn.Rows.Add(dr);
} return dtReturn;
}
Another way to convert linq to data table
public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query){ if (query == null) { throw new ArgumentNullException("query"); } IDbCommand cmd = ctx.GetCommand(query as IQueryable); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = (SqlCommand)cmd; DataTable dt = new DataTable("sd"); try { cmd.Connection.Open(); adapter.FillSchema(dt, SchemaType.Source); adapter.Fill(dt); } finally { cmd.Connection.Close(); } return dt; }
Another way using linq to conversion
var vrCountry = from country in objEmpDataContext.CountryMaster
select new {country.CountryID,country.CountryName};
DataTable dt = LINQToDataTable(objEmpDataContext,vrCountry);
To implement the custom CopyToDataTable<T> methods in your application
public class ObjectShredder<T> { private System.Reflection.FieldInfo[] _fi; private System.Reflection.PropertyInfo[] _pi; private System.Collections.Generic.Dictionary<string, int> _ordinalMap; private System.Type _type; // ObjectShredder constructor. public ObjectShredder() { _type = typeof(T); _fi = _type.GetFields(); _pi = _type.GetProperties(); _ordinalMap = new Dictionary<string, int>(); } /// <summary> /// Loads a DataTable from a sequence of objects. /// </summary> /// <param name="source">The sequence of objects to load into the DataTable.</param> /// <param name="table">The input table. The schema of the table must match that /// the type T. If the table is null, a new table is created with a schema /// created from the public properties and fields of the type T.</param> /// <param name="options">Specifies how values from the source sequence will be applied to /// existing rows in the table.</param> /// <returns>A DataTable created from the source sequence.</returns> public DataTable Shred(IEnumerable<T> source, DataTable table, LoadOption? options) { // Load the table from the scalar sequence if T is a primitive type. if (typeof(T).IsPrimitive) { return ShredPrimitive(source, table, options); } // Create a new table if the input table is null. if (table == null) { table = new DataTable(typeof(T).Name); } // Initialize the ordinal map and extend the table schema based on type T. table = ExtendTable(table, typeof(T)); // Enumerate the source sequence and load the object values into rows. table.BeginLoadData(); using (IEnumerator<T> e = source.GetEnumerator()) { while (e.MoveNext()) { if (options != null) { table.LoadDataRow(ShredObject(table, e.Current), (LoadOption)options); } else { table.LoadDataRow(ShredObject(table, e.Current), true); } } } table.EndLoadData(); // Return the table. return table; } public DataTable ShredPrimitive(IEnumerable<T> source, DataTable table, LoadOption? options) { // Create a new table if the input table is null. if (table == null) { table = new DataTable(typeof(T).Name); } if (!table.Columns.Contains("Value")) { table.Columns.Add("Value", typeof(T)); } // Enumerate the source sequence and load the scalar values into rows. table.BeginLoadData(); using (IEnumerator<T> e = source.GetEnumerator()) { Object[] values = new object[table.Columns.Count]; while (e.MoveNext()) { values[table.Columns["Value"].Ordinal] = e.Current; if (options != null) { table.LoadDataRow(values, (LoadOption)options); } else { table.LoadDataRow(values, true); } } } table.EndLoadData(); // Return the table. return table; } public object[] ShredObject(DataTable table, T instance) { FieldInfo[] fi = _fi; PropertyInfo[] pi = _pi; if (instance.GetType() != typeof(T)) { // If the instance is derived from T, extend the table schema // and get the properties and fields. ExtendTable(table, instance.GetType()); fi = instance.GetType().GetFields(); pi = instance.GetType().GetProperties(); } // Add the property and field values of the instance to an array. Object[] values = new object[table.Columns.Count]; foreach (FieldInfo f in fi) { values[_ordinalMap[f.Name]] = f.GetValue(instance); } foreach (PropertyInfo p in pi) { values[_ordinalMap[p.Name]] = p.GetValue(instance, null); } // Return the property and field values of the instance. return values; } public DataTable ExtendTable(DataTable table, Type type) { // Extend the table schema if the input table was null or if the value // in the sequence is derived from type T. foreach (FieldInfo f in type.GetFields()) { if (!_ordinalMap.ContainsKey(f.Name)) { // Add the field as a column in the table if it doesn't exist // already. DataColumn dc = table.Columns.Contains(f.Name) ? table.Columns[f.Name] : table.Columns.Add(f.Name, f.FieldType); // Add the field to the ordinal map. _ordinalMap.Add(f.Name, dc.Ordinal); } } foreach (PropertyInfo p in type.GetProperties()) { if (!_ordinalMap.ContainsKey(p.Name)) { // Add the property as a column in the table if it doesn't exist // already. DataColumn dc = table.Columns.Contains(p.Name) ? table.Columns[p.Name] : table.Columns.Add(p.Name, p.PropertyType); // Add the property to the ordinal map. _ordinalMap.Add(p.Name, dc.Ordinal); } } // Return the table. return table; } }
public static class CustomLINQtoDataSetMethods { public static DataTable CopyToDataTable<T>(this IEnumerable<T> source) { return new ObjectShredder<T>().Shred(source, null, null); } public static DataTable CopyToDataTable<T>(this IEnumerable<T> source, DataTable table, LoadOption? options) { return new ObjectShredder<T>().Shred(source, table, options); } }
Convert datatable to list
STEP 1:
List<MyClassObject> liMyClassObject=myConvesionObject.GetDetails(yourdatatable);
STEP 2:
class myConvesionObject
{
public List<MyClassObject> GetDetails(DataTable dtDetails) { return MyConversionClass.ConvertToList<MyClassObject>(dtDetails); }
}
STEP 3: my conversion class
public static class MyConversionClass { /// <summary> /// Convert DataTable ToList /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <returns></returns> public static List<T> ConvertToList<T>(this DataTable table) where T : new() { Type t = typeof(T); // Create a list of the entities we want to return List<T> returnObject = new List<T>(); // Iterate through the DataTable's rows foreach (DataRow dr in table.Rows) { // Convert each row into an entity object and add to the list T newRow = dr.ConvertToEntity<T>(); returnObject.Add(newRow); } // Return the finished list return returnObject; } /// <summary> /// ConvertTo Entity /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tableRow"></param> /// <returns></returns> public static T ConvertToEntity<T>(this DataRow tableRow) where T : new() { // Create a new type of the entity I want Type t = typeof(T); T returnObject = new T(); foreach (DataColumn col in tableRow.Table.Columns) { string colName = col.ColumnName; // Look for the object's property with the columns name, ignore case PropertyInfo pInfo = t.GetProperty(colName.ToUpper(), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); // did we find the property ? if (pInfo != null) { object val = tableRow[colName]; // is this a Nullable<> type bool IsNullable = (Nullable.GetUnderlyingType(pInfo.PropertyType) != null); if (IsNullable) { if (val is System.DBNull) { val = null; } else { // Convert the db type into the T we have in our Nullable<T> type val = Convert.ChangeType (val, Nullable.GetUnderlyingType(pInfo.PropertyType)); } } else { // Convert the db type into the type of the property in our entity val = Convert.ChangeType(val, pInfo.PropertyType); } // Set the value of the property with the value from the db pInfo.SetValue(returnObject, val.ToString().Trim().ToUpper(), null); //pInfo.SetValue(returnObject, val.ToString().ToUpper(), null); } } // return the entity object with values return returnObject; } /// <summary> /// Convert DataRow[] ToList /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <returns></returns> public static List<T> ConvertToList<T>(this DataRow[] dtRows) where T : new() { Type t = typeof(T); // Create a list of the entities we want to return List<T> returnObject = new List<T>(); // Iterate through the DataTable's rows foreach (DataRow dr in dtRows) { // Convert each row into an entity object and add to the list T newRow = dr.ConvertToEntity<T>(); returnObject.Add(newRow); } // Return the finished list return returnObject; } public static List<EntityClass> ConvertGridEntity<T>(this List<T> liValues, int Pno, int RecPage, List<string> listr) where T : new() { Type t = typeof(T); Type Et = typeof(EntityClass); // Create a list of the entities we want to return List<EntityClass> returnObject = new List<EntityClass>(); Type gType = typeof(T); int licount = liValues.Count; int StartInd = ((Pno) * RecPage + 1); int EndInd = Convert.ToInt32(((Pno + 1) * RecPage) > licount ? licount : ((Pno + 1) * RecPage)); for (int ind = StartInd; ind <= EndInd; ind++) { T genType = liValues[ind - 1]; EntityClass EC = new EntityClass(); PropertyInfo[] EntitypropInfo = EC.GetType().GetProperties(); //EntityClass E = new EntityClass(); PropertyInfo[] propInfo = genType.GetType().GetProperties(); Array.Sort(propInfo, new DeclarationOrderComparator()); int j = 0; foreach (string str in listr) { int i = Convert.ToInt32(str); j = j + 1; if (!string.IsNullOrEmpty(string.Format("{0}", propInfo[i].GetValue(genType, null)))&&j<16) { var value = propInfo[i].GetValue(genType, null).ToString().ToUpper(); // Look for the object's property with the columns name, ignore case PropertyInfo pInfo = Et.GetProperty("C" + j + "", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); //pInfo.SetValue(genType, value, i); pInfo.SetValue(EC, value, null); } } returnObject.Add(EC); } // Return the finished list return returnObject; } } public class DeclarationOrderComparator : IComparer { int IComparer.Compare(Object x, Object y) { PropertyInfo first = x as PropertyInfo; PropertyInfo second = y as PropertyInfo; if (first.MetadataToken < second.MetadataToken) return -1; else if (first.MetadataToken > second.MetadataToken) return 1; return 0; } }
LIST TO XML CONVETIONS
STEP 1:
List<myListClass> mylistObjects=new List<myListClass>();
string mystringxml=myclassconversion.PrepareSaveXml(mylistObjects)
STEP 2:
class myclassconversion
{
public string PrepareSaveXml(List<myListClass> liValues) { return ListToXMLCLass.GetXml<myListClass>(liValues, "RootNode", "ChildNode"); }
}
STEP 3:
public static class ListToXMLCLass { /// <summary> /// Preparing Save XML string with GenericType /// </summary> /// <typeparam name="T"></typeparam> /// <param name="liValues"></param> /// <param name="parentRoot"></param> /// <param name="childRoot"></param> /// <returns></returns> public static string GetXml<T>(List<T> liValues,string parentRoot,string childRoot) { XDocument xDoc = new XDocument(); var partentRoot = new XElement(parentRoot); foreach (T genType in liValues) { PropertyInfo[] propInfo = genType.GetType().GetProperties(); var childroot = new XElement(childRoot); foreach (PropertyInfo prop in propInfo) { if (prop.PropertyType.FullName.ToUpper() == typeof(System.String).ToString().ToUpper() || prop.PropertyType.FullName.ToUpper() == typeof(System.Int32).ToString().ToUpper() || prop.PropertyType.FullName.ToUpper() == typeof(System.Double).ToString().ToUpper()) { if (prop.Name.ToLower() != "parentrootnode" && prop.Name.ToLower() != "parentnode" && prop.Name.ToLower() != "childnode") { if (!string.IsNullOrEmpty(string.Format("{0}", prop.GetValue(genType, null)))) childroot.SetAttributeValue(prop.Name, GTKString.ToEscapeSpecialChars(prop.GetValue(genType, null).ToString())); } } } partentRoot.Add(childroot); } xDoc.Add(partentRoot); return xDoc.ToString(); } public static XElement GetEntityXml<T>(T genClass, string RootNode) { XDocument xDoc = new XDocument(); PropertyInfo[] propInfo = genClass.GetType().GetProperties(); var childroot = new XElement(RootNode); foreach (PropertyInfo prop in propInfo) { if (prop.Name.ToLower() != "parentrootnode" && prop.Name.ToLower() != "parentnode" && prop.Name.ToLower() != "childnode") { if (!string.IsNullOrEmpty(string.Format("{0}", prop.GetValue(genClass, null)))) childroot.SetAttributeValue(prop.Name, GTKString.ToEscapeSpecialChars(prop.GetValue(genClass, null).ToString())); } } // xDoc.Add(childroot); return childroot; } }
No comments:
Post a Comment