C# Converting List<int> to List<double> - c#

I have a List<int> and I want to convert it to a List<double>. Is there any way to do this other than just looping through the List<int> and adding to a new List<double> like so:
List<int> lstInt = new List<int>(new int[] {1,2,3});
List<double> lstDouble = new List<double>(lstInt.Count);//Either Count or Length, I don't remember
for (int i = 0; i < lstInt.Count; i++)
{
lstDouble.Add(Convert.ToDouble(lstInt[0]));
}
Is there a fancy way to do this? I'm using C# 4.0, so the answer may take advantage of the new language features.

You can use Select as suggested by others, but you can also use ConvertAll:
List<double> doubleList = intList.ConvertAll(x => (double)x);
This has two advantages:
It doesn't require LINQ, so if you're using .NET 2.0 and don't want to use LINQBridge, you can still use it.
It's more efficient: the ToList method doesn't know the size of the result of Select, so it may need to reallocate buffers as it goes. ConvertAll knows the source and destination size, so it can do it all in one go. It can also do so without the abstraction of iterators.
The disadvantages:
It only works with List<T> and arrays. If you get a plain IEnumerable<T> you'll have to use Select and ToList.
If you're using LINQ heavily in your project, it may be more consistent to keep using it here as well.

You can use LINQ methods:
List<double> doubles = integers.Select<int, double>(i => i).ToList();
or:
List<double> doubles = integers.Select(i => (double)i).ToList();
Also, the list class has a ForEach method:
List<double> doubles = new List<double>(integers.Count);
integers.ForEach(i => doubles.Add(i));

You could do this using the Select extension method:
List<double> doubleList = intList.Select(x => (double)x).ToList();

You can use ConvertAll method inside of .Net Framework 2.0 here is an example
List<int> lstInt = new List<int>(new int[] { 1, 2, 3 });
List<double> lstDouble = lstInt.ConvertAll<double>(delegate(int p)
{
return (double)p;
});

You can use a method group:
lstDouble = lstInt.Select(Convert.ToDouble)

You can use Select or ConvertAll. Keep in mind that ConvertAll is available in .Net 2.0 too

Related

How to sort following list

I have following var result = new List<Tuple<int, List<ProductionReportEntry>, int>>();
How I can sort it by the last integer , that the result will be from high to Low .
Thanks for help.
The easiest way is to use LINQ's OrderByDescending() extension method, it will sort your list in descending order from high to low and push it back into the list:
result = result.OrderByDescending(t => t.Item3).ToList();
That's assuming you want to store it back int the original reference, of course you could assign it to another variable, etc...
Alternatively, you could do an in-place sort using List.Sort()'s overload that takes a Comparisson<T> delegate:
// does descending since we put r on the lhs and l on the rhs...
result.Sort((l, r) => r.Item3.CompareTo(l.Item3));
Alternatively, you could build a custom IComparer<T>, of course for your Tuple<int, List<PropertyReportEntry>, int> but that gets pretty ugly looking...

Remove elements from one List<T> that are found in another

I have two lists
List<T> list1 = new List<T>();
List<T> list2 = new List<T>();
I want remove all elements from list1, which also exist in list2. Of course I can loop through the first loop looking for each element in list2, but I am looking for elegant solution.
Thanks!
To change the actual list1 in place, you could use
list1.RemoveAll(item => list2.Contains(item));
You might instead prefer to simply have a query over the lists without modifying either
var result = list1.Except(list2);
LukeH makes a good recommendation in the comments. In the first version, and if list2 is particularly large, it might be worth it to load the list into a HashSet<T> prior to the RemoveAll invocation. If the list is small, don't worry about it. If you are unsure, test both ways and then you will know.
var theSet = new HashSet<YourType>(list2);
list1.RemoveAll(item => theSet.Contains(item));
With LINQ:
var result = list1.Except(list2);
list1.RemoveAll( item => list2.Contains(item));
Description
I think you mean the generic type List<Type>. You can use Linq to do this
Sample
List<string> l = new List<string>();
List<string> l2 = new List<string>();
l.Add("one");
l.Add("two");
l.Add("three");
l2.Add("one");
l2.Add("two");
l2.Add("three");
l2.Add("four");
l2.RemoveAll(x => l.Contains(x));
More Information
MSDN - List.RemoveAll Method
var result = list1.Except(list2);
Using LINQ you can do this:
List1.RemoveAll(i => !List2.Contains(i));
If you want to remove a list of objects (list2) from another list (list1) use:
list1 = list1.Except(list2).ToList()
Remember to use ToList() to convert IEnumerable<T> to List<T>.
var NewList = FirstList.Where(a => SecondList.Exists(b => b.ID != a.ID));
Using LINQ

How can I switch that code to use LINQ

I know that is good practice use LINQ instead of iterative loops, can I modify this code to use LINQ?
List<string> priorsLstIDs = ServiceUtil.extractColumnValuesAsStringVals(tqrPriors,Helper.STUDY_ID);
List<DateTime> priorsLstDates = ServiceUtil.extractColumnValuesAsDateTimeVals(tqrPriors, "STUDY_DATE");
List<PriorElemSt> priorsElemLst = new List<PriorElemSt>(priorsLstIDs.Count);
PriorElemSt elem;
for (int i = 0; i < priorsLstIDs.Count; i++)
{
elem = new PriorElemSt(priorsLstIDs[i], priorsLstDates[i]);
priorsElemLst.Add(elem);
}
return filterStudyPriors(priorsElemLst);
Thanks.
Update: can the call to filterStudyPriors() method can be part of the LINQ?
IEnumerable<PriorElemSt> priorsElemLst = priorsLstIDs.Select((s,i) => new PriorElemSt(s, priorsLstDates[i]));
return filterStudyPriors(priorsElemLst);
You could use the Enumerable.Range method like so:
//first get the range of indexes
var range = Enumerable.Range(0, priorsLstIDs.Count);
//now project a list of elements at each index
var priorsElemLst = range.Select(i => new PriorElemSt(priorsLstIDs[i], priorsLstDates[i])).ToList();
You can use the Zip method
var priorsElemLst = priorsLstIDs.Zip(
priorsLstDates, (i, d) => new PriorElemSt(i, d))
In the above statement i is the item from priorsLstIds and d the item from priorsLstDates. They will be 'zipped' together using their positions in their lists.
it is not a best practice at all but only if you think it will improve the readability against a performance loss.
LINQ-to-Objects generally is going to add some marginal overheads (multiple iterators, etc). It still has to do the loops, and has delegate invokes, and will generally have to do some extra dereferencing to get at captured variables etc.
Is a LINQ statement faster than a 'foreach' loop?

How to convert List<int> to string[]?

I need an easy way to convert a List<int> to a string array.
I have:
var the_list = new List<int>();
the_list.Add(1);
the_list.Add(2);
the_list.Add(3);
string[] the_array = new string[the_list.Count];
for(var i = 0 ; i < the_array.Count; ++i)
the_array[i] = the_list[i].ToString();
...which looks to be very ugly to me.
Is there an easier way?
Note: I'm looking for an easier way - not necessarily a faster way.
Use LINQ:
string[] the_array = the_list.Select(i => i.ToString()).ToArray();
I know you have a good answer, but you don't need LINQ or Select. You can do it with a ConvertAll and an anonymous method. Like this:
var list = new List<int>();
....
var array = list.ConvertAll( x => x.ToString() ).ToArray();
Similar idea, but I think this is not linq. in case that matters.
Sorry, I don't have .NET installed on this machine, so totally untested:
var theList = new List<int>() { 1, 2, 3 };
var theArray = theList.Select(e => e.ToString()).ToArray(); // Lambda Form
var theArray = (from e in theList select e.ToString()).ToArray(); // Query Form
List has a ToArray() method. It will save you typing but probably won't be more efficient.
Because your list only has a number, you can easily convert them to a string. Just create a loop and convert its members to the string.
string[] the_array = new string[the_list.Count];
int i=0;
foreach(var item in the_list)
{
the_array[i] = item.ToString();
i++;
}

Best way to do a split and convert the result into ints

I have a DB table that contains a comma separated list of ID's (ints) that are stored as nvarchar.
I have a get method to return these in one hit as a list. At the moment I think I'll have to do something like this:
List<int> ids = new List<int>();
string[] pageids = experssion.Split(separators)
foreach (string number in pageids)
{
ids.Add(Convert.ToInt32(number));
}
Can anyone think of a nicer way to do this ? Can I do it all on the split somehow ?
I'd to it like this:
var ids = expression.Split(separator).Select(s => int.Parse(s));
It uses the Linq extensions of .NET 3.0. As an alternative (saves one lambda), you could also do this which is arguably less readable:
var ids = expression.Split(separator).Select((Func<string, int>)int.Parse);
If you're not using C# 3.0, or aren't a fan of LINQ, you could do it the C# 2.0 way:
// This gives you an int[]
int[] pageids = Array.ConvertAll(expression.Split(separator), new Converter<string,int>(StringToInt));
// Add each id to the list
ids.AddRange(pageids);
public static int StringToInt(string s)
{
return int.Parse(s);
}
EDIT:
Or, even simpler as per Konrad's suggestion:
int[] pageids = Array.ConvertAll<string,int>(expression.Split(separator),int.Parse);
ids.AddRange(pageids);
With LINQ you can do this:
List<int> ids
= expression
.Split(separators)
.Select(number => Convert.ToInt32(number))
.ToList()

Categories

Resources