I have a Linq query as below.
var DataSource = from m in product
select new { Class = m.Class, Id = (new Make(m.Id)).ProductName};
I instantiate a class called Make and fetch the ProductName based on the Id.
Some of the Id's are 0.
Is there a way I can exclude all the Id's that are 0?
Sure, just do this:
var DataSource = from m in product
where m.Id != 0
select new
{
Class = m.Class,
Id = (new Make(m.Id)).ProductName
};
You're looking for the where clause:
where m.Id != 0
var DataSource = from m in product
where m.Id != 0
select new
{
Class = m.Class,
Id = (new Make(m.Id)).ProductName
};
Try this:
var DataSource = from m in product
where m.Id != 0
select new { Class = m.Class, Id = (new Make(m.Id)).ProductName};
Related
I need to get some Field's out of the Group using linq for example, this is my code:
(from PaymentTypes in PaymentTypes_DataTable.AsEnumerable()
join CashTransactions in CashTransactions_DataTable.AsEnumerable()
on PaymentTypes.Field<Int32>("cashpaymenttype_id")
equals CashTransactions.Field<Int32>("cashpaymenttype_id")
into JoinedCashTransactions
from CashTransactions in JoinedCashTransactions.DefaultIfEmpty()
group CashTransactions by PaymentTypes.Field<Int32>("cashpaymenttype_id")
into GroupPaymentTypes
select new
{
cashpaymenttype_id = 0, // Get PaymentTypeID
cashpaymenttype_name = "", // Get PaymentTypeName
cashtransaction_amount = GroupPaymentTypes.Sum(a =>
a != null
? (a.Field<Int32>("cashtransactionstatus_id") == 1 ||
a.Field<Int32>("cashtransactionstatus_id") == 3 ? 1 : -1) *
a.Field<Double>("cashtransaction_amount")
: 0.00),
}).Aggregate(PaymentTypesTransactions_DataTable, (dt, result) => {
dt.Rows.Add(result.cashpaymenttype_id, result.cashpaymenttype_name,
result.cashtransaction_amount); return dt; });
This linq works but i need to get the fields cashpaymenttype_id and cashpaymenttype_name they are within PaymentTypes
Assuming PaymentTypeID - PaymentTypeName is 1-to-1, you could change your group by to this:
group CashTransactions by new
{
PaymentTypeId = PaymentTypes.Field<Int32>("cashpaymenttype_id"),
PaymentTypeName = PaymentTypes.Field<String>("cashpaymenttype_name")
}
into GroupPaymentTypes
The your select will look like this:
select new
{
cashpaymenttype_id = GroupPaymentTypes.Key.PaymentTypeId,
cashpaymenttype_name = GroupPaymentTypes.Key.PaymentTypeName,
...
}
Having:
Initialize an anonymouse collection (I would send it as json)
var myCollection = new[]
{
new
{
Code = 0,
Name = "",
OtherAttribute = ""
}
}.ToList();
myCollection.Clear();
And get the data.
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
I want to add an Identity column, I need the collection ordered and a counted from 1 to collection.count. Is for binding this counter to a Column in a table (jtable).
var myCollection = new[]
{
new
{
Identity = 0,
Code = 0,
Name = "",
OtherAttribute = ""
}
}.ToList();
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Identity = Enum.Range(1 to n)//Here I donĀ“t know how to do; in pl/sql would be rownum, but in Linq to SQL how?
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
If you are using linq to entities or linq to sql, get your data from the server and ToList() it.
Most likely this answer will not translate to sql but I have not tried it.
List<string> myCollection = new List<string>();
myCollection.Add("hello");
myCollection.Add("world");
var result = myCollection.Select((s, i) => new { Identity = i, Value = s }).ToList();
As Simon suggest in comment, that could would look like below:
int counter = 0; //or 1.
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Identity = counter++,
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
Is there any problem in executing this kind of code?
As Simon stated in his comments, consider the following, albeit contrived, example:
int i = 0;
var collection = Enumerable.Range(0, 10).Select(x => new { Id = ++i });
One solution that helped me to achieve the same goal:
Create a separate Function like this:
private int getMaterialOrder(ref int order)
{
return order++;
}
Then call it in your linq query like:
...
select new MaterialItem() { Order=getMaterialOrder(ref order),
...
I have two lists as follows:
var SeparatedEmployees = (from s in DataContext.HRM_EMP_TRMN.AsEnumerable()
where s.TRMN_FINL_STUS == "SA" && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on s.EMP_CODE equals e.EMP_CODE
where e.ACTIVE_STATUS == "A"
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
var ConfirmedEmployees = (from c in DataContext.HRM_EMP_FINL_STMT_MST.AsEnumerable()
where ((Convert.ToDateTime(c.FINL_STMT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(c.FINL_STMT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on c.EMP_CODE equals e.EMP_CODE
join s in DataContext.HRM_EMP_TRMN on c.EMP_CODE equals s.EMP_CODE
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
Tyring to remove the items from the first list, which are also in second list.
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ConfirmedEmployees.Contains(item)
select item).ToList();
Tried this one too:
FinalSeparatedEmployees = SeparatedEmployees.Except(ConfirmedEmployees).ToList<HRM_EMP_FINL_STMT_MSTModel>();
But not getting the accurate result. What I'm missing? Thanks.
Its better to use EMP_CODE because your objects are not comparable.
var ids = ConfirmedEmployees.Select(x => x.EMP_CODE).ToList();
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ids.Contains(item.EMP_CODE)
select item).ToList();
Using this model, I would like to perform a left outer join of the course table to the student table and display them with a search dropdown menu on the courses.
My MVC code is :
var query = from c in db.Students
join o in db.Enrollments on c.StudentID equals o.StudentID
join co in db.Courses on o.CourseID equals co.CourseID into sr
from x in sr.DefaultIfEmpty()
select new Student
{
FirstName=c.FirstName,
LastName=c.LastName,
EnrollmentDate=c.EnrollmentDate,
MiddleName=c.MiddleName,
StudentID=c.StudentID
//StudentName = c.FirstName.ToString(),
//CourseID = x.CourseID.ToString(),
//CourseName = x.Title.ToString()
//== null ? -1 : x.Title
};
if (!string.IsNullOrEmpty(course))
{
students = query.Where(x => x.CourseName == course).Select(item=>new Student(){FirstName = c.FirstName.ToString()}).ToList();
}
return View(students);
But I can't get it to work. Can someone please enlighten me on how to correctly do this.
This is the sample screen :
public List<Student> GetStudentsByCourseName(string courseName)
{
var list = new List<Student>();
var course = db.Courses.SingleOrDefault(o => o.Title == courseName);
if (course != null)
{
list = course.Enrollments.Select(o => new Student {
FirstName = o.Student.FirstName,
LastName = o.Student.LastName
}).ToList();
}
return list;
}
I'm working with entity framework database and I want to populate my dropdownlist from a table but in right order.
Right now i'm using the code:
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
List<object> sDataValue = new List<object>();
sDataValue.Add("- Select -");
sDataValue.Remove("Other");
foreach (var vData in databaseList)
{
sDataValue.Add(vData.SkillName);
}
sDataValue.Add("Other");
DropDownListDB.DataSource = sDataValue.ToArray();
DropDownListDB.DataBind();
This is the Solution
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
orderby p.skill_name != "Other" descending, p.skill_name
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
Remove the entry -Select- from the list and append it as first item to your List<object>:
List<object> sDataValue = new List<object>();
sDataValue.Add("-Select-");
foreach (var vData in databaseList){}
would be the easiest way, I assume.
EDIT
then you will use if/else, maybe and
foreach (var vData in databaseList){} //fill your list
sDataValue.Add("-Other-");
You could add a "section id" to your database: 0 for "-Select-", 2 for "Other", 1 for the rest. Then sort on 1) section ID, 2) name.
But it would be best not to store that "-Select-" at all (it doesn't represent a valid value) and add it in the correct spot after the databind.
Just do this:
Remove -Select- and Other from databaseList like this:
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
&& p.skill_name.ToLower() !="other"
&& p.skill_name.ToLower() !="-select-"
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
and then do this:
DropDownListDB.DataSource = sDataValue.ToArray().OrderBy(s=>s);
DropDownListDB.Items.Insert(0, "-Select-");
DropDownListDB.Items.Add("Other");
if you must bring -Select- and Other field from database, binding them to the DropDownList and then removing them and again inserting them at appropriate location is little expensive.
You simply don't pick those two rows from the database. it will be more efficient.
You can try play with orderby with boolean value
orderby p.skill_name != "Other" descending, p.skill_name
In your code =>
var databaseList = from p in db.TECHNICAL_SKILLS
where p.skill_type == "Database"
orderby p.skill_name != "Other" descending, p.skill_name
select new EmployeeTechnicalSkillInfo
{
TechnicalSkillId = p.technical_skill_id,
SkillType = p.skill_type,
SkillName = p.skill_name
};
List<object> sDataValue = new List<object>();
sDataValue.Add("- Select -");
foreach (var vData in databaseList)
{
sDataValue.Add(vData.SkillName);
}
DropDownListDB.DataSource = sDataValue.ToArray();
DropDownListDB.DataBind();