LINQ:检查列表中的其他项目

时间:2013-05-28 11:07:04

标签: c# 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列表,其中包含不同的分组ID。让我们说

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是重复的)..我将如何删除重复的检查

3 个答案:

答案 0 :(得分:3)

作为一项简单的更改,请尝试在p.Id != answer.Id行中为p.Id > answer.Id兑换groupItems.Where(...)

答案 1 :(得分:0)

你的意思是:

        var items = new List<Tuple<int, int>>()
        {
            new Tuple<int, int>(1, 1)
            , new Tuple<int, int>(1, 2)
            , new Tuple<int, int>(2, 2)
            , new Tuple<int, int>(2, 2)
            , new Tuple<int, int>(2, 3)
            , new Tuple<int, int>(3, 2)
            , new Tuple<int, int>(3, 3)
            , new Tuple<int, int>(4, 4)
            , new Tuple<int, int>(4, 3)
            , new Tuple<int, int>(4, 4)
        }.Select(kp => new { id = kp.Item1, data = kp.Item2 });

        var res = (
            from i1 in items
            from i2 in items
            where i1.id < i2.id
                /* Custom Filter goes there */
                && i1.data == i2.data
            select new { i1 = i1, i2 = i2 }
        );

答案 2 :(得分:-2)

试试这个

var pairs = Enumerable.Range(0, items.Count()).SelectMany(index => 
  items.Skip(index + 1).Select(right => new { left = items.elementAt(index), right }));

var matches = pairs.Where(item => 
               (item.left.Weight - item.right.Weight) > item.left.Tolerance);

第一部分创建所有必须比较的对,如(1,2),(1,3),(2,3),对于3个项目的集合。 第二部分选择符合条件的对。

我还删除了你已经想到的分组代码(items = groupItems)。

相关问题