2015-07-20 47 views
2
 // removing duplicities from Dictionary 
     var removables = data.ToLookup(x => x.Value, x => x.Key) 
      .SelectMany(x => x.Skip(1)).ToList(); 
     foreach (var key in removables) 
      data.Remove(key); 

卸下duplicities此代码工作得很好具有低于输入(数据):从字典

102030;"http://xxx.yyy.com/102030.ashx" 
102030;"http://xxx.yyy.com/102030_x.ashx" 

102030;"http://xxx.yyy.com/102030_x.ashx"被去除。

但是,当我把这个输入:

102030;"http://xxx.yyy.com/102030_x.ashx" 
102030;"http://xxx.yyy.com/102030.ashx" 

102030;"http://xxx.yyy.com/102030.ashx"被删除。 但我只需要删除包含'_'的项目。

如何解决这个问题?是否可以按长度对输入进行排序或调整linq查询?

+0

确保您始终只有2个重复值,并且只有一个带有下划线?如果您有3个或更多重复项,并且其中有2个或更多重复项存在下划线,或者这种情况是不可能的? – Leron

+0

你真的应该根据实际的过滤器进行过滤,而不是猜测要跳过哪个索引。你的输入是字符串还是别的? – Sayse

+0

什么是过滤出url的确切标准,跳过所有那些带下划线的? –

回答

1

如果你想跳过带有下划线的元素,你不应该跳过第一个元素,但仍然是所有元素,而无需下划线:

// smart removing duplicities from Dictionary 
var removables = data.ToLookup(x => x.Value, x => x.Key) 
        .SelectMany(x => x.Where(y => !y.Key.Contains('_')).ToList(); 
foreach (var key in removables) 
    data.Remove(key); 
1

如果马克Shevchenkos答案不浮动你的船无论出于何种原因,可以很好如果你想按长度排序。

我创建了一个List<KeyValuePair<int, string>>类型的虚拟数据源,因为字典不允许重复键。

卸下重复然后直线前进:

  1. 组由Key
  2. 订购价值长度
  3. 以每groupset

    var source = new List<KeyValuePair<int, string>>() { 
    new KeyValuePair<int,string>(102030, "http://xxx.yyy.com/102030.ashx"), 
    new KeyValuePair<int,string>(102030, "http://xxx.yyy.com/102030_x.ashx"), 
    new KeyValuePair<int,string>(102040, "http://xxx.yyy.com/102040_x.ashx"), 
    new KeyValuePair<int,string>(102040, "http://xxx.yyy.com/102040.ashx"), 
    new KeyValuePair<int,string>(102050, "http://xxx.yyy.com/102050.ashx"), 
    new KeyValuePair<int,string>(102050, "http://xxx.yyy.com/102050_x.ashx"), 
    new KeyValuePair<int,string>(102060, "http://xxx.yyy.com/102060_y.ashx"), 
    new KeyValuePair<int,string>(102060, "http://xxx.yyy.com/102060.ashx") 
    

    }的第一结果;

    source.GroupBy (s => s.Key) 
         .Select(x => x.OrderBy (y => y.Value.Length)) 
         .Select (x => x.First()) 
         .Dump(); 
    
0

非常感谢您对您的解决方案。

我找了下:

 var removables = dict.OrderBy(x => x.Key).ToLookup(x => x.Value, x => x.Key).SelectMany(x => x.Skip(1)).ToList(); 
     foreach (var key in removables) 
      dict.Remove(key); 

我只重点增加订货,现在我已经正确排序设置:-)

谢谢您的评论此解决方案。