Home > Back-end >  Use listbox SelectedItems as LINQ argument
Use listbox SelectedItems as LINQ argument

Time:05-06

I have a list filled with class entries:

public class Package
{
    private readonly string _packageID = string.Empty;
    private readonly string _packageStatus= string.Empty;

    public Package(string package_ID, string package_status)
    {
        _packageID = package_ID;
        _packageStatus= package_status;
    }

    public string PackageID
    {
        get
        {
            return _packageID;
        }
    }

    public string PackageStatus
    {
        get
        {
            return _packageStatus;
        }
    }
 }

Based on this class I fill a list with data:

List<Package> PackageList = new List<Package>();
PackageList.Add(new Package(0, "New");
PackageList.Add(new Package(1, "Processed");
PackageList.Add(new Package(2, "Processed");
PackageList.Add(new Package(3, "New");
PackageList.Add(new Package(4, "Sent");
PackageList.Add(new Package(4, "Received");

This data is displayed in a datagridview:

dataGridView1.DataSource = PackageList

The various package statuses are displayed in a listbox:

listBox1.DataSource = PackageList.Select(p => p.PackageStatus).Distinct().ToList();

Using this listbox the user can select multiple statuses and update the list with Packages in the datagridview.

I would like to use LINQ to retrieve all Packages from the PackageList based on the selected statuses in the listbox. I have tried multiple thing but no success untill now....

SubPackageList = PackageList.Where(o => o.PackageStatus == Listbox1.SelectedItems);

Any support on how to approach this is highly appreciated.

CodePudding user response:

If I correctly understand, you end up with a list of Packages and a list of conditions, and you need the matching elements.

List<Package> PackageList = new List<Package>();
PackageList.Add(new Package(0, "New"));
PackageList.Add(new Package(1, "Processed"));
PackageList.Add(new Package(2, "Processed"));
PackageList.Add(new Package(3, "New"));
PackageList.Add(new Package(4, "Sent"));
PackageList.Add(new Package(4, "Received"));

List<string> Conditions = new List<string>() { "New", "Processed"};

var SubList = PackageList.Where(x => Conditions.Contains(x.PackageStatus)).ToList();
            
foreach (var item in SubList)
{
    Console.WriteLine($"ID:{item.PackageID}  Status:{item.PackageStatus}");
}

Returns:

ID:0  Status:New
ID:1  Status:Processed
ID:2  Status:Processed
ID:3  Status:New

Can check it here

  • Related