Remove Duplicate/Existing value from dropdownlist - c#

I will like to generate a dropdownlist with unique value.
However i only able to generate an original dropdownlist which generated from database.
At my language table it contain 3 languages:
-ENG , GER, KOR
for the language i already used for a question list:
- KOR
So the result bind to dropdownlist should:
- ENG, GER
My Controller code:
List<SelectListItem> langResult = new List<SelectListItem>();
///// Ori Language
var result = from r in db.SURV_Language_Model
select r.Language;
///// Used Language
var result2 = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
orderby s.Question_Position ascending
where r.Qext_Question_ID == Question_ID
select new { r, s };
/////Remaining Language
result 3 = result 2 - result 1 <==*** Pseudo code
foreach (var item in result3)
{
SelectListItem temp = new SelectListItem();
temp.Text = item;
temp.Value = item;
langResult.Add(temp);
}
ViewBag.LangList = langResult;
My View Code:
#Html.LabelFor(model => model.Language)
#Html.DropDownListFor(model => model.Language, ViewBag.LangList as IEnumerable<SelectListItem>)
#Html.ValidationMessageFor(model => model.Language, "*")
Anyway to perform this?

Was fixed by code below, hope can help you all:
List<SelectListItem> langResult = new List<SelectListItem>();
var result = from r in db.SURV_Language_Model
select r.Language;
var result2 = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
orderby s.Question_Position ascending
where r.Qext_Question_ID == Question_ID
select r.Qext_Language;
List<string> list = new List<string>(result);
List<string> list2 = new List<string>(result2);
for (int x = 0; x < list.Count(); x++ )
{
if ( x < list2.Count())
{
if (list[0].ToString() == list2[x].ToString())
{
list.Remove(list[0].ToString());
}
}
}
foreach (var item in list)
{
SelectListItem temp = new SelectListItem();
temp.Text = item;
temp.Value = item;
langResult.Add(temp);
}
ViewBag.LangList = langResult;

Related

Split a string value in list using linq

I have a list with a column value like "0000000385242160714132019116002239344.ACK" i need to take last 6 digits from this value like "239344" without extension(.ack) when binding to the list.
And i need to find the sum of Salary field also.
My query looks like below.
var result = from p in Context.A
join e in B on p.Id equals e.Id
join j in Context.C on e.CId equals j.CId
where (e.Date >= periodFrom && e.Date <= periodTo)
group new
{
e,
j
} by new
{
j.J_Id,
e.Date,
e.Es_Id,
e.FileName,
j.Name,
e.ACK_FileName,
p.EmpSalaryId,
p.Salary
} into g
orderby g.Key.CId, g.Key.Es_Id, g.Key.Date, g.Key.FileName
select new
{
CorporateId = g.Key.CId,
ProcessedDate = g.Key.Date,
EstID = g.Key.Es_Id,
FileName = g.Key.FileName,
Name = g.Key.Name,
ack = g.Key.ACK_FileName,
EmpSalaryId = g.Key.EmpSalaryId,
Salary=g.Key.Salary
};
var Abc=result.ToList();
var result = (from p in Context.A
join e in B on p.Id equals e.Id
join j in Context.C on e.CId equals j.CId
where (e.Date >= periodFrom && e.Date <= periodTo)
group new { e, j } by new
{
j.J_Id,
e.Date,
e.Es_Id,
e.FileName,
j.Name,
ACK_FileName = e.ACK_FileName.Substring(e.ACK_FileName.IndexOf(".ACK") - 7, 11),
p.EmpSalaryId,
p.Salary
} into g
orderby g.Key.CId, g.Key.Es_Id, g.Key.Date, g.Key.FileName
select new
{
CorporateId = g.Key.CId,
ProcessedDate = g.Key.Date,
EstID = g.Key.Es_Id,
FileName = g.Key.FileName,
Name = g.Key.Name,
ack = g.Key.ACK_FileName,
EmpSalaryId = g.Key.EmpSalaryId,
Salary = g.Sum(item => item.Salary)
}).ToList();

How to select the entire top row group by some fields using linq

I try to select an item from a list, which has the highest frequency for a filed, so I group items based on that filed and sort them descending. Now I want to select the top row.
I tried:
private Rule MatchRule(string cond)
{
var results = (from x in rules
where x.Cond == cond
group x by new { x.Tree.Val , r = x.Tree.Right.Val, l = x.Tree.Left.Val}
into g
select new {
rule = ???,
Count=g.Count(),
}).OrderByDescending(x => x.Count).ToList();
return results[0].rule;
}
What should I use instead of ??? to select all the fields of an item (the entire item) (the top row).
I found it, I must use First() to select the entire row
private Rule MatchRule(string cond)
{
var results = (from x in rules
where x.Cond == cond
group x by new { x.Tree.Val , r = x.Tree.Right.Val, l = x.Tree.Left.Val}
into g
select new {
rule = g.First(),
Count=g.Count(),
}).OrderByDescending(x => x.Count).ToList();
return results[0].rule;
}

Show XML node value in MVC view by number of similar node?

Is there anyway to group the xml node value by similar into number? I had tried to output the value as below but i can't get the out as what i want. Please guide me on this. Thanks!
My Answer_Data Sample in database: (After extract will get the C1 and C2)
Question_ID | Answer_Data
==============================================
1 | <Answer_Data><Answer>C1</Answer>
2 | <Answer_Data><Answer>C2</Answer>
3 | <Answer_Data><Answer>C2</Answer>
String[] data after extract using Linq:
["c1","c2","c2"]
Able to View in MVC:
c1
c2
c2
What i want is:
c1 - 1
c2 - 2
My Controller:
public ActionResult SURV_Answer_Result(int Survey_ID, string Language = "ENG")
{
List<AnswerQuestionViewModel> viewmodel = new List<AnswerQuestionViewModel>();
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals
s.Question_ID
select new { r, s };
var viewModel = new AnswerQuestionViewModel();
viewModel.Survey_ID = Survey_ID;
string[] resultanswer = new string[queryResult.Count()];
foreach (var item in query.ToList())
{
string str = item.s.Answer_Data;
XElement qconfig;
qconfig = XElement.Parse(str);
string value = item.s.Question_Type;
int i = 0;
switch (value)
{
case "Choices":
{
XElement ChoicesType =
(from node in qconfig.Elements("ChoicesType")
select node).SingleOrDefault();
viewModel.ChoiceType = ChoicesType.Value;
XElement ChoicesAns =
Here is i get the answer data ===>> (from node in qconfig.Elements("Answer")
select node).SingleOrDefault();
resultanswer[i++] = ChoicesAns.Value;
viewModel.ResultAnswer = resultanswer;
}
break;
case "Multiple_Line":
{
// do nothing
}
break;
viewmodel.Add(new AnswerQuestionViewModel()
{
ResultAnswer = viewModel.ResultAnswer
});
}
return View(viewmodel);
}
}
My View:
if (Model[i].ChoiceType == "SingleChoice")
{
for (int x = 0; x < Model[i].ResultAnswer.Count(); x++)
{
#Html.LabelFor(m => m[i].Answer, Model[i].ResultAnswer[x].ToString(),new{ #class="qlabel2" })
<br/>
}
}
As you are stating in question that you are receiving array of element than you just try group by like this
string[] strarray = new string[] {"c1","c2","c2"};
var groups = from str in strarray
group str by str into g
select new {
key = g.Key,
count = g.Count()
}
try group by using linq like this
var xmlstr="<root><Answer_Data><Answer>C1</Answer></Answer_Data>
<Answer_Data><Answer>C2</Answer></Answer_Data>
<Answer_Data><Answer>C2</Answer></Answer_Data></root>";
XDocument xmldoc = XDocument.Parse(xmlstr);
var groups = from record in xmldoc.Descendants("Answer_Data")
group record by (string)record.Element("Answer")
into g
select new {
key = g.Key,
count = g.Count()
}

how to get the number of repetitions from List<int>

List<int> ListIdProducts = new List<int>();
var IdProductKey = from a in me.ProductKeywords where a.Keyword == item.Id select a;
foreach (var item2 in IdProductKey)
{
ListIdProducts.Add(item2.Product.Value);
}
Result is:
5
6
7
5
2
5
I need to get the following 5=3, 6=1, 7=1, 2=1
Use GroupBy LINQ method:
ListIdProducts
.GroupBy(i => i)
.Select(g => new { Value = g.Key, Count = g.Count() });
var query1 = from a in ListIdProducts
group a by new { a } into g
select new
{
item = g.Key,
itemcount = g.Count()
};
This a fairly standard group-by problem.
//untested
var IdProducts = from a in me.ProductKeywords
where a.Keyword == item.Id
group by a.Product.Value into g
select g.Count();

Compare lists and get values with Linq

My object is "MyClass" with 2 properties : Id (int) and HourBy (int)
I have two list :
var List1 = new List<MyClass>();
var List2 = new List<MyClass>();
I'd like to get one list with :
- Object from List1 present in List2 based on Id with Hourby (list2) < Hourby in List1
- Object from List1 no present in List2
//#Sample1
//List1 :
List1.add(new MyClass(1,10));
List1.add(new MyClass(2,20));
List1.add(new MyClass(3,30));
//List2 :
List2.add(new MyClass(1,10));
List2.add(new MyClass(2,15));
//I'd like to get :
new MyClass(2,5);
new MyClass(3,30);
//Sample2
List1 :
List1.add(new MyClass(1,10));
List1.add(new MyClass(2,20));
List1.add(new MyClass(3,30));
//List2 :
List2.add(new MyClass(1,10));
List2.add(new MyClass(2,15));
List2.add(new MyClass(2,2));
//I'd like to get :
new MyClass(2,3);
new MyClass(3,30);
Thanks,
You can do this by the following Linq statement:
var result = List1.Where(x => !List2.Select(y => y.Id).Contains(x.Id)
|| List2.Single(y => x.Id == y.Id).HourBy < x.HourBy);
Best Regards
I think this is what you're after, based on the example lists you supplied...
var list3 = new List<MyClass>();
foreach(var item in list1)
{
var totalFromOther = list2.Where(x => x.id == item.id).Sum(y => y.HourBy);
var newItem = new MyClass() { id = item.Id, HourBy = item.HourBy - totalFromOther };
if(newItem.HourBy > 0)
list3.Add(newItem);
}
Here's a solution:
var qry = from ee in
(from e1 in list1
join e2 in list2 on e1.Id equals e2.Id into gj
from e in gj.DefaultIfEmpty()
select new {
e1.Id,
MainHourBy = e1.HourBy,
SecondHourBy = (e == null ? 0 : e.HourBy)
})
where ee.SecondHourBy < ee.MainHourBy
group ee by ee.Id into g
select new MyClass
{
Id = g.Key,
HourBy = g.First().MainHourBy - g.Sum(el => el.SecondHourBy)
};
I use this code, it's not perfect but working and may be clearer for newbie in Linq (like me)
List< MyClass> listRes = new List< MyClass>();
foreach ( MyClass item in list1)
{
var exist = list2
.Select(x => x.MyClass)
.Contains(item);
if (!exist)
listRes.Add(item);
else
{
var totalFromOther = list2
.Where(x => x.MyClass.Id == item.Id)
.Sum(y => y.HourBy);
if (item.HourBy != totalFromOther)
{
item.HourBy = item.HourBy - totalFromOther;
listRes.Add(item);
}
}
}
Thanks for you help,
var agg1 = from l in list1
group l by l.ID into g
select new { g.Key, Sum = g.Sum(_ => _.HourBy) };
var agg2 = from l in list2
group l by l.ID into g
select new { g.Key, Sum = g.Sum(_ => _.HourBy) };
var q = from l1 in agg1
let l2 = agg2.FirstOrDefault(_ => _.Key == l1.Key)
let sum = l1.Sum - (l2 != null ? l2.Sum : 0)
where sum != 0
select new MyClass(l1.Key, sum);
var list3 = q.ToList();
//Group list 2, so there is one entry per ID, with HourBy = total hour by
var summedL2 = from item2 in List2
group item2 by item2.ID into g
select new Test(g.Key, g.Sum(item => item.HourBy));
var result =
//Select items from list1
from item1 in List1
//Left join to our summed List2
join item2s in summedL2 on item1.ID equals item2s.ID into tempItem2s
from item2 in tempItem2s.DefaultIfEmpty()
//Where there is no match, or item2 is < item1
where (item2 == null || item2.HourBy < item1.HourBy)
//Select a new Test object, with the HourBy changed
select new Test(item1.ID, item1.HourBy - (item2 == null ? 0 : item2.HourBy));

Categories

Resources