I've constructed a List with two items that have Selected = true.
When creating a SelectList with the List, no items are selected.
var y = superlistItemsList.Where(x => x.Selected).ToList();
model.SuperlistItems = new SelectList(superlistItemsList, "Value", "Text");
var f = model.SuperlistItems.Where(x => x.Selected).ToList();
y has a count of 2, while f has a count of 0. Why is this the behaving in this way?
Related
I want get two atributes int for a List:
I try :
List<int> idsAgrupados = listMain.Select(x => new { x.productID, x.personalID}).Cast<int>().ToList();
but this way I get a conversion error.
you can use like this:
List<int> firstList = data.Select(x => x.firstId).ToList();
List<int> secondList = data.Select(x => x.secondId).ToList();
List<List<int>> g = new List<List<int>>()
{
firstList,
secondList
};
If you want to convert all the attributes in select of lambda then convert each item individually.
List<int> idsAgrupados = listMain.Select(x => new { productID = Convert.ToInt32(x.productID), personalID = Convert.ToInt32(x.personalID) }).ToList();
Let me know if you face any error in this.
I have this class where the query must result in this list a property.
This property must check on table how many duplicated exists.
This code works, but its very slow. can you help me ?
var lst = _uow.Repository.GetAll();
var query =
from p in lst
select new GetRfqResponse
{
ID = p.ID,
//bad performance
Count = lst.Where(x => x.Property == p.Property).AsQueryable().Count(),
//
};
Counting in a queryable list can be easily achieved using the Count() function:
// Find duplicated names
var byName = from s in studentList
group s by s.StudentName into g
select new { Name = g.Key, Count = g.Count() };
Check this fiddle to see it running.
Below is for InMemory
GroupBy should come to help.
var propertyGroupedList = list.GroupBy(l=>l.Property);
var query = list.Select(l => new GetRfqResponse{
Id = l.Id,
Count = propertyGroupedList.First(g=> g.Key == l.Property).Count()
});
Or you can create a dictionary with key as "Property" and value as count, then you will have to loop just once to store the count.
This allows you to get count in constant time
Dictionary<string, int> map = new Dictionary<string, int>();
foreach (var item in lst)
{
if (!map.ContainsKey(lst.Property))
{
map.Add(item.Property, 1);
}
else
map[item.Property]++;
}
var z = lst.Select(l => new GetRfqResponse{
Id = l.ID,
Count = map[l.Property]
});
I have a List<Returns> as below
Item ManCode ShippedQty
ITM01 A10 1
ITM02 A11 2
ITM01 A10 3
Here the first and 3 rd rows have same values for Item and Mancode. in this case, the both the items should be merged and shippedQty values must be added to 4.
There should be only 2 items in the final list
You can try to use linq GroupBy with Sum function.
list.GroupBy(x=> new{x.Item ,x.ManCode}).Select(
x=> new {
Item = x.key.Item,
ManCode = x.key.ManCode,
ShippedQty = x.Sum(y=>y.ShippedQty)
}
);
var result = items.GroupBy(x => new { x.Item, x.ManCode })
.Select(x => new Returns
{
Item = x.Key.Item,
ManCode = x.Key.ManCode,
ShippedQty = x.Sum(y => y.ShippedQty)
}).ToList();
Just try:
List<Returns> list = new List<Returns>(){ /*populate list here*/ };
list = list
.GroupBy(i => new {i.Item, i.ManCode})
.Select(g => new {g.Key.Item, g.Key.ManCode, g.Sum(i => i.ShippedQty)} );
You could use Linq to group the objects on Item and ManCode and sum the quantity like this:
var data = new List<Element>
{
new Element{ Item ="ITM01", ManCode = "A10", ShippedQty = 1},
new Element{ Item ="ITM02", ManCode = "A11", ShippedQty = 2},
new Element{ Item ="ITM01", ManCode = "A10", ShippedQty = 3},
};
var datagrp = (from q in data
group q by new { q.Item, q.ManCode } into p
select new Element
{ Item = p.Key.Item, ManCode = p.Key.ManCode,
ShippedQty = p.Sum(s => s.ShippedQty)}).ToList();
I have a list in my code that I need to filter through and return specific rows based on two criteria. The List in question is a list of models from a database. There are two ID properties on each model, one is the ID from the data table and is unique, the other is an ID we use to identify groups and can repeat. We'll call them ID and GroupID. Basically, I want the resulting list to have only one of each GroupID, and it should be the one with the highest (numerically speaking) ID. For example:
Input:
List<MyModel> modelList = new List<MyModel>
modelList[0].ID = 1 modelList[0].GroupID = 5
modelList[1].ID = 2 modelList[1].GroupID = 5
modelList[2].ID = 3 modelList[2].GroupID = 6
modelList[3].ID = 4 modelList[3].GroupID = 6
Desired Output:
Models at indexes 1 and 3.
Using LINQ:
var items = (from model in modelList
group model by model.GroupID into modelGroup
select modelGroup.Max(i => i.ID)).ToList();
What you have to do here is first order the modelList by ID and then GroupBy the list items by GroupID, then pull the item with max Id value.
var result = modelList.OrderByDescending(x => x.ID).GroupBy(x => x.GroupID).Select(x => x.First());
the above query will give you the result.
This is your solution:
var myData = models.GroupBy(model => model.GroupId)
.Select(group => group.OrderByDescending(model => model.Id).First());
Or you could also do this:
var myData = models.GroupBy(model => model.GroupId)
.Select(group => group.First(model => model.Id == group.Max(model1 => model1.Id)));
For fun, here's a fiddle.
You can try to use GroupBy.
var q = modelList.GroupBy(x => x.GroupID, x => x,
(key, g) => new {
GroupID = key,
Id = g.Max(c => c.ID)
});
This should group all your elements by GroupId and select Max ID in one of that groups.
Try this code:
List<MyModel> modelList = new List<MyModel>();
modelList.Add(new MyModel());
modelList.Add(new MyModel());
modelList.Add(new MyModel());
modelList.Add(new MyModel());
modelList[0].ID = 1; modelList[0].GroupID = 5;
modelList[1].ID = 2; modelList[1].GroupID = 5;
modelList[2].ID = 3; modelList[2].GroupID = 6;
modelList[3].ID = 4; modelList[3].GroupID = 6;
var list = from ml in modelList group ml by ml.ID into r select new { ID = r.Key, MaxGroupID = r.Max() };
this might help you
modelList.GroupBy(model => model.GroupId, g => g.Id).Select(item => item.Max())
var newModelList = modelList.GroupBy(ml => ml.GroupID)
.Select(g => new MyModel
{
ID = g.OrderByDescending(x => x.ID).First().ID,
GroupID = g.Key
}).ToList();
Details
1) GroupBy then Select to get distinct items over GroupID.
2) First() after OrderByDescending to get highest ID.
3) new MyModel in Select is just to be explicit about the projection.
I need to retrieve an average TimeSpan from a List of grouped objects, but have no idea where to start.
Each object in the list has a property of type TimeSpan and I've grouped the List by another property. Now I need the average TimeSpan from each group.
List<Item> Items = new List<Item>();
Item _item1 = new Item { Category = "A", Duration = _someTimeSpan1};
Item _item2 = new Item { Category = "B", Duration = _someTimeSpan2};
Item _item3 = new Item { Category = "A", Duration = _someTimeSpan3};
Items.Add(_item1);
Items.Add(_item2);
Items.Add(_item3);
var _groupedItems = Items.GroupBy(i => i.Category);
In the above example _item1 and _item3 are grouped on Category and I need the average of Duration for those two items that are in the group.
Any help is appreciated.
foreach (var group in _groupedItems) {
var avg = TimeSpan.FromSeconds(group.Average(i => i.Duration.TotalSeconds));
}
var _groupedItems = Items.GroupBy(i => i.Category)
.Select(g => new { Cat = g.Key,
Avg = new TimeSpan(Convert.ToInt64(g.Select(x=>x.Duration.Ticks).Average())) });
That should do the trick:
foreach (var group in _groupedItems){
Console.WriteLine(group.Average(g => g.Duration.TotalMilliseconds));
}