0

我有像下面这样的课

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

4

3 回答 3

3

作为一个简单的更改,请尝试在您的线路中p.Id != answer.Id进行交换。p.Id > answer.IdgroupItems.Where(...)

于 2013-05-28T12:16:56.677 回答
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 }
        );
于 2013-05-28T11:40:23.997 回答
-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);

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

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

于 2013-05-28T11:42:45.173 回答