我的代码中有一个列表,我需要根据两个条件筛选并返回特定的行。有问题的列表是数据库中的模型列表。每个模型上有两个ID属性,一个是数据表中的ID,是唯一的,另一个是我们用来识别组的ID,可以重复。我们称他们为ID和GroupID。基本上,我希望结果列表只有每个GroupID中的一个,它应该是具有最高(数字)ID的那个。例如:
输入:
public static bool IsSimilarValuesExist(string value)
{
var result = false;
double productSimilarity = 0;
double publisherSimilarity = 0;
List<string> products = FilterListWithFirstOrSecondCharacter(value, ServicesMail.GetAllProductNames());
List<string> publishers = FilterListWithFirstOrSecondCharacter(value, ServicesMail.GetAllPublisherNames());
IStringMetric metric = new Levenstein();
foreach (var item in products)
{
if (metric.GetSimilarity(value, item) * 100 > 80)
{
productSimilarity = metric.GetSimilarity(value, item) * 100;
}
}
foreach (var item in publishers)
{
if (metric.GetSimilarity(value, item) * 100 > 80)
{
publisherSimilarity = metric.GetSimilarity(value, item) * 100;
}
}
var averageSimilarity = productSimilarity * publisherSimilarity / 2;
if (averageSimilarity >= 80)
{
result = true;
}
return result;
}
期望输出:
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
答案 0 :(得分:2)
使用LINQ:
var items = (from model in modelList
group model by model.GroupID into modelGroup
select modelGroup.Max(i => i.ID)).ToList();
答案 1 :(得分:1)
您需要做的是首先按ID排序modelList,然后按GroupID对列表项进行GroupBy,然后使用max Id值拉出项目。
var result = modelList.OrderByDescending(x => x.ID).GroupBy(x => x.GroupID).Select(x => x.First());
以上查询将为您提供结果。
答案 2 :(得分:0)
var newModelList = modelList.GroupBy(ml => ml.GroupID)
.Select(g => new MyModel
{
ID = g.OrderByDescending(x => x.ID).First().ID,
GroupID = g.Key
}).ToList();
详细
1)GroupBy
然后Select
获取GroupID
上的不同商品。
2)First()
OrderByDescending
获得最高ID
。
3)new MyModel
中的Select
只是要明确投射。
答案 3 :(得分:0)
您可以尝试使用GroupBy。
var q = modelList.GroupBy(x => x.GroupID, x => x,
(key, g) => new {
GroupID = key,
Id = g.Max(c => c.ID)
});
这应该按GroupId
对所有元素进行分组,然后在其中一个组中选择Max ID
。
答案 4 :(得分:0)
试试这段代码:
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() };
答案 5 :(得分:0)
SaveChanges
答案 6 :(得分:0)
这是你的解决方案:
var myData = models.GroupBy(model => model.GroupId)
.Select(group => group.OrderByDescending(model => model.Id).First());
或者您也可以这样做:
var myData = models.GroupBy(model => model.GroupId)
.Select(group => group.First(model => model.Id == group.Max(model1 => model1.Id)));
为了好玩,here's小提琴。