Home > Software design >  How can I convert from "System.Collections.GenericList<Artikel>" to "Artikel&qu
How can I convert from "System.Collections.GenericList<Artikel>" to "Artikel&qu

Time:03-31

   public List<Racun> IzdaniRacun { get; }
    public List<Artikel> ZalogaArtiklov { get; }
    public List<RezerviranArtikel> ZalogaRezerviraniArtiklov { get; }

    public Lekarna(List<Racun> izdaniRacuniList, List<Artikel> zalogaArtiklov, List<RezerviranArtikel> zalogaRezerviraniArtiklovList)
    {
        IzdaniRacun = izdaniRacuniList;
        ZalogaArtiklov = zalogaArtiklov;
        ZalogaRezerviraniArtiklov = zalogaRezerviraniArtiklovList;
    }

    //void rezervirajArtikel(Artikel artikel, Oseba oseba), ki artikel premakne iz zaloge in ga uvrsti na seznam rezerviranih artiklov
    public void rezervirajArtikel(Artikel artikel, Oseba oseba)
    {
        List<Artikel> selected = ZalogaArtiklov.Where(a => a.Id == artikel.Id).ToList();
        selected.ForEach(item => ZalogaArtiklov.Remove(item));

        ZalogaRezerviraniArtiklov.AddRange(new RezerviranArtikel(selected, oseba));

        foreach (Artikel a in ZalogaArtiklov)
        {
            Console.WriteLine(a);
        }

        foreach (RezerviranArtikel a in ZalogaRezerviraniArtiklov)
        {
            Console.WriteLine(a);
        }
    }

RezerviranArtikel Class

using System;
using System.Collections.Generic;

public class RezerviranArtikel 
{
    // Pripravite razred RezerviranArtikel, ki vsebuje artikel in osebo za katero je artikel rezerviran.
    public Artikel Artikel { get; }
    public Oseba Oseba { get; }

    public RezerviranArtikel(Artikel artikel, Oseba oseba)
    {
        Artikel = Artikel;
        Oseba = oseba;
    }
}

I basically have to move the item from one list (Article) to another, (ReservedArticle) by removing item from one list and adding it to the oher one.

But I am having a problem with fixing this error becuase I can not conver from List to an object named "Artikel". Do you have any suggestions on how to fix that error?

Error: CS1503 Argument 1: cannot convert from 'System.Collections.Generic.List' to 'Artikel'

on this line of code:

ZalogaRezerviraniArtiklov.AddRange(new RezerviranArtikel(selected, oseba));

CodePudding user response:

You want to use :

ZalogaRezerviraniArtiklov.AddRange(selected.Select(article => new RezerviranArtikel(article, oseba));

because you want to convert each Artikel in selected list to RezerviranArtikel, not just one element.

CodePudding user response:

As you are using .AddRange method then it looks like you want to add a collection of RezerviranArtikel. So your code will look like this:

ZalogaRezerviraniArtiklov.AddRange(selected.Select(selectedArticle => new 
    RezerviranArtikel(selectedArticle, oseba));
  •  Tags:  
  • c#
  • Related