I have List<object> that seems above, I want to convert it to List<string>.
How can I convert it ?
I need List<string> that has 6 items (11:00,13:45,.... etc)
var mylist = myObjectList.ConvertAll(x => x.ToString());
Edit
var mylist = myObjectList.ConvertAll(x => Convert.ToString(x));
thanks Scott Chamberlain
To get first array of objects
var mylist = (myObjectList.First() as object[]).ToList()
.ConvertAll(x=>Convert.ToString(x));
To add rest to the list.
mylist.AddRange(mylist.GetRange(1,myObjectList.Count-2).ConvertAll(x=>Convert.ToString(x)));
var stringList = yourObjectList.OfType<string>().ToList();
Remember to add the namespace System.Linq;
The OfType is needed to convert the array to an array<T> which is necessary in order to use it with LINQ
Try this
List<string> stringlist = objectList.Cast<string>()
.ToList();
If you're not certain about those elements are strings you can use Select
List<string> stringlist = objectList.Select(x=> x.ToString())
.ToList();
To avoid NullReferenceException in case of null values try the following
List<string> stringlist = objectList.Where(x=> x != null)
.Select(x=> x.ToString())
.ToList();
Using LINQ this is fairly easy. If you are sure they are all strings you can simply do
int i = //Some code that sets i, like a for loop
var oldList = seanceInfo.theatre[i].seances;
List<string> newList = oldList.Cast<string>().ToList();
If you are not sure all of the objects are strings you need to perform some kind of conversion, however that is just as easy
List<string> newList = oldList.Select(o => Convert.ToString(o)).ToList();
From your comment: "seances is List<object>, and first index of seances is object[]. I need these items.", I think what you really want may be a SelectMany
List<string> info = seanceInfo.theatre.SelectMany(x => x.seances).Select(x => Convert.ToString(x)).ToList();
This will take each seance in each theater and combine it in to one master list.
You can simply cast it using LinQ.
myObjectList.Cast<string>();
Or filter all non-string
myObjectList.OfType<string>();
Casting like :
var list = (List<String>) listObjects.
Related
I have an string array and a list of string. For example,
string[] stringArray = {"car", "bike", "truck"};
List<string> stringList = new List<string>{"car_blue", "car_red", "truck_yellow", "ship_black", "rocket_orange"};
From the array and list, I want to compare stringArray with stringList and retrieve items that are in the stringArray and is also part of the stringList.
Eg: the items retrieved should be, 'car_blue', 'car_red' and 'truck_yellow'?
You could use LINQ' Where to filter the stringList using the parts before the _:
var result = stringList.Where(x => stringArray.Contains(x.Split('_')[0]));
You have to Split by _ to get all tokens, then you can use Intersect...Any:
var itemsInBoth = stringList.Where(s => stringArray.Intersect(s.Split('_')).Any());
If you want to ignore the case, so also accept Car_Yellow:
var itemsInBoth = stringList.Where(s => stringArray.Intersect(s.Split('_'), StringComparer.OrdinalIgnoreCase).Any());
The Best way where you don't have to use split is
string[] oneMinEnabledTime = stringList.Where(x => stringArray.Any(ele => x.ToLower().Contains(ele.ToLower()))).ToArray();
or if you want list
List<string> oneMinEnabledTime = stringList.Where(x => stringArray.Any(ele => x.ToLower().Contains(ele.ToLower()))).ToList();
I have the following code inside my asp.net mvc-5 & ET-6 :-
List<String> ScannedResourceNames = new List<String>();
if (scaninfo.Any(a => a.VMList.Any(a2 => a2.Resource.RESOURCENAME.ToLower() == vmname.ToLower())))
{
ScannedResourceNames.Add(vmname.ToLower());
}
List<String> allcurrentresourcename = scaninfo.SelectMany(a => a.VMList.Select(a2 => a2.Resource.RESOURCENAME)).ToList();
List<String> finallist = allcurrentresourcename.Except(ScannedResourceNames).ToList();
currently the allcurrentresourcename have 3 items :
A
B
C
while ScannedResourceName have 1 item :
B
So i though when i define .Except i will get 2 items (A& C) in the finallist var. but the final list will have 3 items (A,B,C). so can anyone advice on this please ?
You can use one of the standard StringComparer properties to ignore case.
List<String> finallist = all.Except(these, StringComparer.InvariantCultureIgnoreCase)
.ToList();
Probably related to case, because when you fill the ScannedResourceNames list you're ignoring it:
a2.Resource.RESOURCENAME.ToLower() == vmname.ToLower()))
But Except uses the Equals implementation which is case-sensitive.
If you don't want to use the comparer, that should do the trick too:
List<String> finallist = allcurrentresourcename.Where(r =>
!ScannedResourceNames.Contains(r.ToLower())
.ToList();
Is there a easy way to find duplicates in list, and then sort them by number of appearance? Also, duplicates should be removed.
Eg. you have a List<String> like this:
List<String> = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
Question is, how to convert this list into -> "6", "1", "2", "4", "5"?
use Linq.Distinct()
List<String> list = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
list = list.Distinct().ToList();
If you actually want them ordered from most common to least - unlike your example -
var ordered = list
.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Select(g => g.Key);
should achieve this.
I think the simplest way is to use LINQ method Distinct():
var originalList = …;
vat withoutDuplicates = originalList.Distinct();
Though you should note that the order of the result of Distinct() is explicitly left undocumented.
Using System.Linq;
// Assuming inputList was the original string list
List<String> deDuped = inputList.Distinct().ToList();
Not quite the cleanest yet, but this provides the correct result.
var originalData = new List<string>{"6","1","2","2","4","6","5","1","6","6","2"};
var result = new List<string>();
foreach (var myString in originalData)
{
if (!result.Exists(s => s == myString))
result.Add(myString);
}
Since it's unclear exactly what you mean, here's a solution for two possible meanings:
Get a unique list ordered by the number of occurrences:
Group the list and sort by Count():
List<String> list = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
var q = from s in list
group s by s into g
orderby g.Count() descending
select g.Key;
Get a unique list ordered by the FIRST occurrence of the item in the list
There are already several suggestions to use Distinct, however the documentation DOES NOT GUARANTEE that they appear in the order they appear in the list (the current Enumerable implementation happens to order them that way, but for other providers it's not guaranteed):
Remarks
The result sequence is unordered.
To guarantee order, add an OrderBy clause:
var q = list.Distinct().OrderBy(s => list.IndexOf(s));
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
I have a class that is defined like this:
class A
{
int contractID;
string name;
string blah;
etc...
}
Multiple ClassA are stored stored in List(). I and to create a List based off all the ContractID's in List. Is there a way in LINQ to be able to do this instead of iterating through List()?
You can use the Select extension method to create a projection of the contractID. Like:
var listOfClass = new List<ClassA>(); //Or however you get your list.
var contractIDs = listOfClass.Select(x => x.contractID).ToList();
var onlyContractIDs = myList.Select(x => x.contractID).ToList()
List<ClassA> input = ...;
List<int> output = input.Select(a => a.contractID).ToList();
Select is a generic method. Explicitly specified, it would be Select<ClassA, int>, specifying the input and output types.
The ToList() at the end converts from an IEnumerable<int> to a List<int>, and it does the iteration over the input list now, rather than when the IEnumerable<int> is enumerated.
If you have a List you can make a List with LINQ like this
List<int> contractIDs = mycollection.Select(a => a.ContractID).ToList();
var list = new List<ClassA>();
...
list.Select(a => a.ContractID);