how to use distinct in linq for Non-key field [closed] - linq

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
how can i get below result with linq?
key salesID prodname
1 2566 a
2 2566 b
3 3647 c
4 3012 d
result
salesID prodname
2566 b
3647 c
3012 d
i want clear all duplicatesalesIDand i use this code but doesn't work
var n = (from p in context.ArefSms where p.Stautos != true select p).Distinct().OrderBy(x => x.SalesID).ToList();

The simplest approach is probably to use GroupBy:
var result = context.MyTable
.GroupBy(x => x.Field1)
.Select(g => new { Field1 = g.Key,
Field2 = g.First().Field2 });
That might give "a" or it might give "b" for the Field2 value... you haven't made it clear whether or not that's important, or how duplicate values of Field1 should be handled, basically.
EDIT: So with your real properties, I suspect you want:
var query = context.ArefSms
.Where(p => !p.Stautos)
.GroupBy(p => p.SalesID)
.Select(g => new { SalesID = g.Key,
ProdName = g.First().ProdName })
.OrderBy(x => x.SalesID);

Related

LINQ group by null issue

I am working on LINQ query where I need all the questions where each question may or may not have sub-question.
I am getting group by null/ exception issue as some parent question doesn't have child question. I am doing left join followed; group by parent question
(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
from childQuestion in qs.DefaultIfEmpty()
group childQuestion by question into g
select new
{
g.Key,
g
}).ToList();
found the answer
(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
from childQuestion in qs.DefaultIfEmpty()
group childQuestion by question into groupQuestions
select new
{
groupQuestions.Key,
childQuestions = groupQuestions.DefaultIfEmpty() == null? null : groupQuestions
}).ToList();
If you want something like "questions with their sub-questions" cnsider using GroupJoin? instead of an inner join followed by a GroupBy
In small steps:
IQueryable<Question> questions = dbContext.Questions.Where(...)
IQueryable<QuestinoHierarch> subQuestions = Context.QuestionHierarchy;
var questionsWithTheirSubQuestions = questions.GroupJoin( // GroupJoin the questions
subQuestions, // with the subQuestions
question => question.Id, // from every question take the Id
subQuestion => subQuestion.ParentQuestionId,
// from every subQuestion take the ParentQuestionId,
(question, subQuestions) => new // take the question with all matching subQuestions
{ // to make one new object:
// select only the question items you plan to use
Title = question.Title,
Priority = question.Priority,
...
// select only the subQuestions that you want (or all)
// for example only the answered sub questions:
SubQuestions = subQuestions
.Where(subQuestion.Type = QuestionType.Answered)
.Select(subQuestion => new
{
// again: select only the subQuestion properties you plan to use
Name = subQuestion.Name,
Date = subQuestion.Date,
...
})
.ToList(),
});
TODO: if desired, make one big statement.

Get null for empty collection in LINQ Group

I am working on LINQ query and part of objective to do SQL database call once to achieve result. I have number of questions which may have collection of answers.
I need to choose all the questions and collection of answer and if there no answer for specific question, I still need it.
for code gives me only question which have answer but not ones without answer
var t3 = (Context.Answers
.Include(answer => answer.AnswerStatusType)
.Where(answer => Context.Questions.Where(q => q.profileId == ProfileId)
.Any(t => t.Id == answer.QuestionId)))
.GroupBy(
x => x.QuestionId,
x => x,
(key, g) => new
{
Question = key,
Answers = g.ToList(),
}
).ToList();
You probably need something like this:
var t3 =
(
from q in Context.Questions
where q.profileId == ProfileId
join a in Context.Answers on q.Id equals a.QuestionId into gas
select new
{
Question = q,
Answers = gas.ToList(),
}
).ToList();
I had the exact same problem and solved it with this giant query, which could probably be optimized, but maybe it will help someone with a similar problem.
// Perform left join to get all the questions (even those that don't have answers)
var results = (from quiz in db.Quizzes
join question in db.Questions on quiz.QuestionID equals question.QuestionID
from answer in db.QuestionAnswers.Where(a => question.QuestionID == a.QuestionID).DefaultIfEmpty()
where quiz.QuizID == quizId
group (answer != null ? new AnswerVM()
{
AnswerId = answer.AnswerID,
AnswerText = answer.AnswerText,
Correct = question.CorrectAnswerID != null ? answer.AnswerID == question.CorrectAnswerID : false,
} : null) // For the questions with no answers
by new
{
question.QuestionID,
question.DisplayOrder,
question.QuestionText,
question.CorrectAnswerID
} into g
select new QuestionVM
{
QuestionId = g.Key.QuestionID,
QuestionText = g.Key.QuestionText,
CorrectAnswerId = g.Key.CorrectAnswerID,
Answers = g.ToList()
})
.AsEnumerable()
.Select(x => {
// If there are no answers then group by will return the list with one value (null),
// then we need to change the answers list to be null (not the list with one null value)
if (x.Answers.Count(a => a != null) <= 0)
{
x.Answers = null;
}
return x;
}).ToList();

how to use 'IN' clause in linq [duplicate]

This question already has answers here:
Where IN clause in LINQ [duplicate]
(8 answers)
Closed 8 years ago.
public static List<mainISRC> comedianlist(int iid)
{
List<mainISRC> newlst = new List<mainISRC>();
ISRCManagementDBEntities1 dbcontext = new ISRCManagementDBEntities1();
newlst=(from z in dbcontext.Comedians
where !(from b in dbcontext.mainISRCs
where b.id==iid && b.Actor1==z.Comedian1 || b.Comedian1==z.Comedian1 || b.Comedian3==z.Comedian1 || b.Comedian4==z.Comedian1).Any()
select z.Comedian1).ToList();
return newlst;
}
I have a table name "comedian" with column 'id','Comedian' and 'IsActive' which contain 50 numbers of rows and also I have another table name "mainISRC" with column 'id','Actor1','Actor2','Actor3','Actor4'. 'id' column in "actorlist" and 'iid' column in "addrecord" are not same.
I have to find all those 'comedian' from "comedian" which are not in 'Actor1','Actor2','Actor3','Actor4' column. What will be the Linq query for this?
Final Update Code
Sorry code is not tested but it may help you or gives you a direction
List<int> liComedianId = new List<int> ();
liComedianId = dbcontext.Comedians.Select(s => (int)s.Id).ToList();
List<mainISRC> limainISRC = new List<mainISRC> ();
limainISRC = dbcontext.mainISRCs.ToList();
var d = ((from a in limainISRC.Select(s => s.Actor1).ToList()
select a).TolList().Union
(from b inlimainISRC.Select(s => s.Actorb).ToList()
select b).Tolist()).ToList();
d = d.Distinct();
licomedianId = licomedianId.Select(s => !d.Contain(s));
List<comedian> LIcomedianFinal = new List<comedian> ();
LIcomedianFinal = dbcontext.Comedians.ToList();
var FinalList =(from a in LIcomedianFinal .ToList()
join b in d.TolIst()
on a.Id equlas d).ToList();

Summing and subtracting in Linq to Sql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello all I want to achieve something like the SQL Select statement with Linq to Sql. Any help will be appreciated.
SELECT SUM(Debit-Credit) AS LBalance FROM dbo.LeaveLedger
WHERE StaffId =1 AND LYEAR='2000'
Assuming Entity Framework:
Context.Table.Where(x => x.StaffId == 1 and x.LYEAR == "2000")
.Sum(y => (y.Debit - y.Credit));
Something like this?
var sum =
db.LeaveLedger
.Where(ll => ll.StaffId == 1 and ll.LYEAR == "2000")
.Sum(ll => (ll.Debit - ll.Credit))
Since Mansfield has already shown the expression syntax, I'll have a go with the classic query:
var LBalance = (from p in dbo.LeaveLedger
where p.StaffId == 1 && p.LYEAR == "2000"
select (p.Debit - p.Credit).Sum();

convert SQL to LINQ group by min, count [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
How convert SQL to LINQ
SELECT
[good_id]
,MIN([good_price]) as minPrice
,Count([distributor_id]) as distrCount
FROM [Provizor].[dbo].[PRICES] where region_id=22
GROUP BY [good_id]
ORDER BY distrCount desc
How to do this in LINQ grouping
Something like this:
var query = dbo.Prices
.Where(x => x.region_id == 22)
.GroupBy(x => x.good_id)
.Select(g => new
{
minPrice = g.Min(x => x.good_price),
distrCount = g.Count(x=> x.distributor_id!=null)
}
.OrderByDescending(x => x.distrCount);

Resources