score:0
ok if you want to avoid forloop
and do it with linq is still possible
here is what i gott
var lista = new list<string>();
lista.add("test");
lista.add("123");
lista.add("5.7");
var listb = new list<type>();
listb.add(typeof(string));
listb.add(typeof(int));
listb.add(typeof(float));
var index =-1;
try{
var newlist = lista.select((x, i)=> convert.changetype(x, listb[(index = i)])).tolist();
}catch(exception e){
throw new exception("failed to cast value "+lista[index]+" to "+listb[index]);
}
score:1
you could zip the lists together, then use the convert.changetype
method
returns an object of a specified type whose value is equivalent to a specified object.
it will throw an exception of the following types
invalidcastexception
this conversion is not supported. -or- value is null and conversiontype is a value type. -or- value does not implement the iconvertible interface.formatexception
value is not in a format recognized by conversiontype.overflowexception
value represents a number that is out of the range of conversiontype.argumentnullexception
conversiontype is null.
example
var lista = new list<string> { "test", "123", "5.7" };
var listb = new list<type> { typeof(string), typeof(int), typeof(int) };
var combined = lista.zip(listb, (s, type) => (value :s, type:type));
foreach (var item in combined)
{
try
{
convert.changetype(item.value, item.type);
}
catch (exception ex)
{
throw new invalidoperationexception($"failed to cast value {item.value} to {item.type}",ex);
}
}
side note: technically speaking this is not casting per se, it's changing/converting the type
score:1
you could do the following with zip.
var result = lista.zip(listb,(value,type)=>
{
try{return convert.changetype(value,(type)type);}
catch{throw new exception($"cannot cast between value {value} to type {type}");}
});
by having the conversion within the zip, would ensure you wouldn't have to convert the whole list if there is an exception earlier in the list.
Source: stackoverflow.com
Related Query
- Convert string[] to int[] in one line of code using LINQ
- Using LINQ to Objects to find items in one collection that do not match another
- Trying to get all elements after first match using linq
- Left outer join using LINQ -- understanding the code
- How to reuse a linq expression for 'Where' when using multiple source tables
- Avoiding code repetition when using LINQ
- Match and update values using linq from two lists?
- Using LINQ to delete an element from a ObservableCollection Source
- LINQ Source Code Available
- Extend a list using last element to match longer list in LINQ zip
- How can I write the following code more elegantly using LINQ query syntax?
- How can I code an outer join using LINQ and EF6?
- C# .Net 3.5 Code to replace a file extension using LINQ
- Trying to understand LINQ code using c#
- Range variable name cannot match the name of a member of the 'Object' class. when querying a DataGridView using Linq
- Retrieve bool result by using LinQ code
- creating Linq to sqlite dbml from DbLinq source code
- read icollection data using LINQ in C# code
- Linq sub query when using a repository pattern with EF code first
- Match all rows on particular day using LINQ to SQL
- Using LINQ query result for data source for GridControl c#
- How to flatten a multi level XML into a single level XML using c# code LINQ
- Using Linq to build a graph class; can you make this code look better?
- How to write this code using the Linq Extension Method-Syntax?
- Code Rewite for tuple and if else statements by using LINQ
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- Using linq to find best match across multiple properties
- Can't add a new record with an integer value into database by using linq from code C#
- Using Linq to find all rows that match these conditions
- Using LINQ to search two lists for match and return boolean for every item
More Query from same tag
- How come Linq functions are available on a variable which can be of a type string
- Returning values with a Func Delegate
- Table not getting updated while using LinQ
- How to tackle complex LINQ queries with outer join?
- Query car price with min and max selection
- How to filter result by a specific value on one field OR a list of values on another field
- Error :the cast to value type "Double" failed because the materialized value is null
- Why I'm still getting System.NotSupportedException
- LINQ GroupBy generated incomplete query
- Linq filter collection with EF
- String array not support in compile query
- Is it possible to set NLS_SORT using Nhibernate configuration?
- select new in linq c#
- How do you write a query that returns an ordered list starting from a specific item?
- Get distinct results using LINQ GroupBy for complex entity relationships?
- Creating A List To Contain LINQ Results?
- Select the Value of custom OrderBy in Linq Query
- Necessary files to deploy for website using linq
- How to convert List of <Entities> to one string with grouping?
- Why XDocument.Load(url) throws exception?
- Using LINQ .Select() to cast into new type is TOO slow?
- How to calculate percentile or ranking of a value in a collection?
- How to order items based on a column in child table in EF
- Entity Framework Core : how can I use DateDiff in Linq?
- How to load XML to List<string>
- "Server failed to resume the transaction" error in SQL Server 2008 + .NET3.5 + LINQ
- Showing First Instance and Last Instance of GroupBy ASP.NET MVC
- search the results by date
- how to create a new item related to a function against previous data in C# linq
- How to query and calculate dates in the where clause of a LINQ statement?