Koray Durudogan Koray Durudogan - 1 month ago 13
C# Question

Get elements of an IEnumerable

I am getting a list of objects like this:

IEnumerable personeller = (IEnumerable)sicil_model.OlayForm_Personel();


I am looping inside it like this

foreach (var personel in personeller)
{
//can't do anything...
}


I am looping inside
personeller
and I can see all elements like this

personeller[0] | { Id = 5, Kimlik = "Koray Durudoğan", EMail = "koray@outlook.com", DepartmanAdi = "Yazilim", PozisyonAdi = "Yazilim Geliştirme" }

personeller[1] | { Id = 6, Kimlik = "Hasan Pınar", EMail = "hasan@dincerelektronik.com.tr", DepartmanAdi = "Yazilim", PozisyonAdi = "Yazilim Geliştirme" }
.
.
.


And goes like this.. The thing is, I can't access elements of objects. For example, how can I get Id of personeller[0] or Kimlik of personeller[1] ?

I made a class like this

public class Personel_Form
{
public int Id { get; set; }
public string Kimlik { get; set; }
public string EMail { get; set; }
public string DepartmanAdi { get; set; }
public string PozisyonAdi { get; set; }
}


but I couldn't manage to convert 'personel' to this class, inside my foreach loop.

Lastly, Here is the method which turns the list:

public object OlayForm_Personel()
{
return (from p in Entity.GetEntity().Sicil
select new
{
Id = p.Id,
Kimlik = p.Isim + " " + p.Soyad,
EMail = p.EMail,
DepartmanAdi = p.Departman.DepartmanAdi,
PozisyonAdi = p.Pozisyon1.PozisyonAdi
}).ToList();
}

Answer

From your sentence of I am looping inside personeller and I can see all elements like this and the given sample data I deduce that the collection returned by the function stores items of the Personel_Form type.

Two options:

  1. You are casting it into the non genetic IEnumerable that holds the items as objects. you can cast it to the correct type:

    IEnumerable personeller = (IEnumerable)sicil_model.OlayForm_Personel();
    
    foreach (var personel in personeller)
    {
        var personalForm = (Personel_Form)personel;
        // personalForm.Kimlik
    }
    
  2. But a better approach is: instead of using the non generic IEnumerable use the generic IEnumerable<T>:

    IEnumerable<Personel_Form> personeller = sicil_model.OlayForm_Personel();
    

As for your latest errors (from comments) it is because your function returns an anonymous type and not the Personel_Form type. Instead if instantiating an anonymous object instantiate a Personel_Form:

public object OlayForm_Personel() 
{
    return (from p in Entity.GetEntity().Sicil
           select new Personel_Form
           {
            Id = p.Id,
            Kimlik = p.Isim + " " + p.Soyad,
            EMail = p.EMail,
            DepartmanAdi = p.Departman.DepartmanAdi,
            PozisyonAdi = p.Pozisyon1.PozisyonAdi
           }).ToList();
}