markzzz
markzzz

Reputation: 48015

How can I use LINQ with dynamic? Generics?

I have this piece of code:

public void RepeaterListato_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
    if (listType == "pages")
    {
        var item = (Pagina)e.Item.DataItem;
        BuildFoto(e, item, IDCategoriaImmaginiPacchettoOfferta);
    }
    else if (listType == "schede")
    {
        var item = (Scheda)e.Item.DataItem;
        BuildFoto(e, item, IDCategoriaImmaginiPacchettoOfferta);
    }
    else if (listType == "news")
    {
        var item = (New)e.Item.DataItem;
        BuildFoto(e, item, IDCategoriaImmaginiPacchettoOfferta);
    }
}

private void BuildFoto(RepeaterItemEventArgs e, dynamic item, string id)
{
    var immagine = item.Immagini.Cast<Allegato>().Where(p => p.Categoria == id).FirstOrDefault();
    if (immagine != null)
    {
        // ...
    }
}

so, due to the type of listType (resolved at Page_Load), the item changes, so I use dynamic. But LINQ doesn't works with Cast and Where on dynamically dispatched opertions.

Is there a workaround? Should I use Generics in your opinions? Best approches?

Upvotes: 0

Views: 63

Answers (1)

vc 74
vc 74

Reputation: 38179

Since you don't have access to the source code of Pagina, Scheda and New, you don't have many options

One is to:

public void RepeaterListato_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
    IEnumerable<Immagini> immagini = null;

    switch (listType)
    {
      case "pages":
        immagini = ((Pagina)e.Item.DataItem).Immagini;
        break;

      case "schede":
        immagini = ((Scheda)e.Item.DataItem).Immagini;
        break;

      case "news":
        immagini = ((New)e.Item.DataItem).Immagini;
        break;
    }

    if (immagini != null)
    {
      BuildFoto(e, immagini, IDCategoriaImmaginiPacchettoOfferta);
    }
}

private void BuildFoto(RepeaterItemEventArgs e, IEnumerable<Immagini> immagini, string id)
{
    var immagine = immagini.Cast<Allegato>().Where(p => p.Categoria == id).FirstOrDefault();
    if (immagine != null)
    {
        // ...
    }
}

Another option is to use reflection to get the immagini collection instance

And yet another option is to create wrapper classes:

public interface IImmaginiContainer
{
  IEnumerable<IImmagine> Immagini { get; }
}

public class NewWrapper : IImmaginiContainer
{
  public NewWrapper(New source)
  {
    _source = source;
  }
  private readonly New _source;

  public IEnumerable<IImmagine> Immagini => _source.Immagini;
}

// Create a similar class for Scheda and Pagina

private void BuildFoto(RepeaterItemEventArgs e, IImaginiContainer item, string id)
{
    var immagine = item.Immagini.Cast<Allegato>().Where(p => p.Categoria == id).FirstOrDefault();
    if (immagine != null)
    {
        // ...
    }
}

Upvotes: 2

Related Questions