Create List<int> from a list<class> - c#

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);

Related

Selection from List of tuple to List of objects C#

In my C# code I have a list List<Tuple<int,string>>. I want to select/convert this to a List<Type>. I want to avoid iterating my list of tuple and insert in other list. Is there any way to do this? Maybe with LINQ?
You cannot change type of list. You only can create new list of another type and fill it with converted values from your list. I suggest to use List<T>.ConvertAll method which exists exactly for this purpose:
List<Tuple<int, string>> tuples = new List<Tuple<int, string>>();
// ...
List<YourType> types =
tuples.ConvertAll(t => new YourType { Foo = t.Item1, Bar = t.Item2 });
You haven't shown this type, but i assume that it contains an int- and a string-property:
List<MyType> result = tupleList
.Select(t => new MyType { IntProperty = t.Item1, StringProperty = t.Item2 })
.ToList();
another option: List.ConvertAll:
List<MyType> result = tupleList.ConvertAll(t => new MyType { IntProperty = t.Item1, StringProperty = t.Item2 });
This presumes that your List<Type> is actually a List<CustomType> (I've called it MyType).
I want to avoid iterating my list of tuple and insert in other list.
LINQ does not avoid loops, it hides them just.

LINQ select more fields of same type

For simple example, I have a class like this:
public class MyClass {
public string name;
public int item1;
public int item2;
}
and a List(MyClass), how do I query the list to create List(int) of both fields item1 and item2? It seems it should be simple but I am struggling a long time.
var result = myList.Select(i => i.item1).ToList() //selects only one field
I know i could use anonymous type but since both item1 and item2 are integers I dont need any new type.
var result = myList.Select(i => new { i.item1, i.item2} ).ToList() //dont need new type, both are integers
how to create list of int? Or did I misunderstood what the anonymous types do?
If you don't like using anonymous types, you could always use a Tuple
var result = myList.Select(i => Tuple.Create(i.item1, i.item2) )
But since both item1 and item2 are integers, you can use an array:
var result = myList.Select(i => new[] { i.item1, i.item2 } )
This will result in a IEnumerable<int[]>. If you want an IEnumerable<int> (with each record's item1 and item2 together in one result set), use SelectMany:
var result = myList.SelectMany(i => new[] { i.item1, i.item2 } )
If you want a flattened list you can do:
List<int> ints = myList.SelectMany(i => new[] { i.item1, i.item2 }).ToList();
if you want to keep the values together you can create a tuple:
List<Tuple<int, int>> pairs = myList.Select(i => Tuple.Create(i.item1, i.item)).ToList():
You can use the following expression for example to create a list containing both items fro all elements of the original list myList.
var result = myList.Select(i => item1).Concat(myList.Select(i => i.item2));

C# Object List to String List

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.

How to flat a IEnumerable by 2 Values?

class AgeClass
{
string[] Names {get;set;}
int Age {get;set;}
}
...
IEnumerable<AgeClass> myList = ...; // a few instances of AgeClass
now i want to get (out of myList) a
IEnumerable<KeyValuePair<string,int>>
with a Pair of Name and Age. How to do this easily?
myList.SelectMany(
x=> x.Names.Select(
z => new KeyValuePair<string,int>(z,x.Age)));
Note that you must be aware that linq is creating a query - each time you enumerate this collection new one will be created based on current state of myList. To remove this effect simply add .ToList() to the end of this line.
Using a query linq syntax:
var result = from el in myList
from n in el.Names
select new KeyValuePair<string, int>(n, el.Age);

C# .NET 3.5 - Performing list like operations on members of a list

I have a field object and I create a list of fields:
class Field {
string objectName;
string objectType;
string fieldName;
string fieldValue;
//constructor...
}
List<Field> fieldList = new List<Field>();
Suppose I wanted to query this list to return a collection of distinct object names (to then be inserted into a checkedlistbox. How would I go about doing that?
I imagine some LINQ magic can manage this?
The expression should return a List of distinct object names from the list as defined. I converted it to a list since the docs for the CheckedListBox DataSource property indicated that it needs to implement IList or IListSource, not merely IEnumerable.
((ListControl)cbListBox).DataSource = fieldList.Select( f => f.objectName )
.Distinct()
.ToList() );
If accessing the checkedListBox as a ListControl doesn't give access to the DataSource (sometimes the docs lie), you could try:
cbListBox.Items.AddRange( fieldList.Select( f => f.objectName )
.Distinct()
.ToArray() );
Either of these work
Using var
1) var fieldNameCollection = from f in fieldList select f.FieldName;
2) Lambda syntax
var fieldNameCollection = fieldList.Select(f => f.FieldName);
Alternately, instead of using var, you can also use
IEnumerable fieldNameCollection = fieldList.Select(f => f.FieldName);
var q = from Field f in fileldList select f.objectName;
chkBoxList.DataSource = q.Distinct();

Categories

Resources