i tried to take one record and skip rest other. my code does not throw any error but does not give any output. here is my code. so please have a look and tell me what is wrong in my code.
public sealed class Person
{
public Person() { }
public Person(string name,bool HQ) {
this.Name = name;
this.HQ = HQ;
}
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private bool _HQ;
public bool HQ
{
get { return _HQ; }
set { _HQ = value; }
}
}
protected void btn_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("HQ", typeof(bool));
DataRow dr = null;
dr = dt.NewRow();
dr["Name"]="Arijit";
dr["HQ"]=true;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Dibyendu";
dr["HQ"] = false;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Tridip";
dr["HQ"] = false;
dt.Rows.Add(dr);
List<Person> oPerson1 = (from c in dt.AsEnumerable()
select new Person
{
Name = c.Field<string>("Name"),
HQ = c.Field<bool>("HQ")
}).Skip(1).Take(2).ToList();
List<Person> oPerson2 = (from c in dt.AsEnumerable()
select new Person
{
Name = c.Field<string>("Name"),
HQ = c.Field<bool>("HQ")
}).Take(1).Skip(2).ToList();
}
if you want to take first record you can call these Take(1)
, First()
, FirstOrDefault()
if you want to take 1 record in the middle call this : Skip(n).Take(1)
where n
- is number of skipped records
When you call Take(n)
- no need to call Skip after that, it have already selected n records
Try this code.
Person oPerson1 = (from c in dt.AsEnumerable()
select new Person
{
Name = c.Field<string>("Name"),
HQ = c.Field<bool>("HQ")
}).First(); //first person in a list
Person oPerson2 = (from c in dt.AsEnumerable()
select new Person
{
Name = c.Field<string>("Name"),
HQ = c.Field<bool>("HQ")
}).Skip(1).First(); //second person in a list
However this code can be rewritten to be clearer:
List<Person> persons = from c in dt.AsEnumerable()
select new Person
{
Name = c.Field<string>("Name"),
HQ = c.Field<bool>("HQ")
};
Person oPerson1 = persons[0];
Person oPerson2 = persons[1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With