C# Get Random Items From List

Select or Get Random Items from List Object in c#

September 17, 2020

City.cs

public class City
{
    public int City_Id { getset; }
    public string City_Title { getset; }
    public int State_Id { getset; }
    public bool active { getset; }
}

Sample City Data

IEnumerable<Citycities = new List<City>()
{
    new City(){ City_Id=1,City_Title="Visakhapatnam",State_Id=1,active=true },
    new City(){ City_Id=2,City_Title="Chittoor",State_Id=1,active=true },
    new City(){ City_Id=3,City_Title="Shimla",State_Id=2,active=true },
    new City(){ City_Id=4,City_Title="Dharamsala",State_Id=2,active=true },
    new City(){ City_Id=5,City_Title="Lucknow",State_Id=3,active=true },
    new City(){ City_Id=6,City_Title="Kanpur",State_Id=3,active=false },
    new City(){ City_Id=7,City_Title="Addison",State_Id=4,active=true },
    new City(){ City_Id=8,City_Title="Allgood",State_Id=4,active=false },
    new City(){ City_Id=7,City_Title="Auburn",State_Id=5,active=true }
};

Retrieve Data Randomly

// GET ALL DATA Randomly
List<CityrandomCityAll = cities.Where(w => w.active).OrderBy(o => System.Guid.NewGuid()).ToList();
 
// GET Only One Data Randomly
City randomCityOne = cities.Where(w => w.active).OrderBy(o => System.Guid.NewGuid()).FirstOrDefault();
 
// GET Three Data Randomly
List<CityrandomCityThree = cities.Where(w => w.active).OrderBy(o => System.Guid.NewGuid()).Take(3).ToList();

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...