检查,对每一个其他项目我有一个像下面LINQ:在列表
public class Item
{
public long Id {get;set;}
public long GroupingId {get;set;}
public long Weight {get;set;}
public long Tolerance {get;set;}
}
现在我有不同的分组标识的Items
列表类。可以说
List<Item> items = GetItems();
现在我需要基于分组的组ID,并检查该组中的每个项目对方。我将如何有效地在LINQ中做到这一点。任何帮助非常感谢。
IDictionary<long, long[]> matches = new Dictionary<long, long[]>();
foreach(groupedItems in items.GroupBy(p=>p.GroupingId))
{
foreach(item in groupItems)
{
// Check item with other items in group items
// and if condition is correct take those 2 items.
// lets say the condition is
// (item.Weighting - other.Weighting) > item.Tolerance
// duplicates could be removed
// lets condition for 1,2 is done means no need to do 2 against 1
var currentItem = item;
var matchedOnes =
groupItems.Where(p => (Math.Abs(p.Weighting - currentItem.Weighting) > currentItem .Tolerance) && p.Id != currentItem.Id)
.ToList();
if (!matchedOnes.Any())
continue;
matches.Add(currentItem.Id, matchedOnes .Select(p=>p.Id).ToArray());
}
}
我不喜欢上面,但其给人重复的(1,2和2,1是重复的)。我将如何删除重复检查
你想要做什么检查?看起来你想抛弃所有差异超过宽容的项目,但在这种情况下,你应该将数值与平均数值进行比较,但是你可以与组中的其他数值进行比较。在这种情况下,如果你有任何差异超过容差的物品,你会扔掉整个组。 –
我需要检查组中两个项目的权重差异大于项目1的容差。 Math.Abs(item1.weighting-item2.weighting)> item1.Tolerance – Lamps
第一使GroupingId 的不同列表喜欢清单 LST = items.Select(H => h.GroupingId).Distinct()。ToList() ; –