2014-11-06 74 views
0

我有以下兩個列表的indexOf數組使用LINQ除了

List<String> list1 = new List<String>(); 
list1.Add("one"); 
list1.Add("two"); 
list1.Add("three"); 
list1.Add("four"); 
list1.Add("five"); 

List<String> list2= new List<String>(); 
list2.Add("one"); 
list2.Add("two"); 
list2.Add("three"); 

IEnumerable<int> indexOfUnwantedColumns; 
indexOfUnwantedColumns = list1.Except(list2) 
           .Select((p, i) => new { Item = p, Index = i }) 
           .Select(p => p.Index); 

正如預期的那樣,這將給予兩項指標在新的清單(0和1)。我希望能夠從原來的列表那裏指數值(3,4)

任何幫助,將不勝感激

+0

怎麼辦'headers'和'placeHolders'涉及到'list1'和'list2'。 – 2014-11-06 12:50:05

+0

我的錯誤,我改變了linq語句中的名字 – 2014-11-06 12:53:53

回答

0

主要思想是之前捕捉到原始索引篩選,然後檢查list2是否包含每個項目。爲了能夠有效地執行這些查找(每查找O(1)聚集的時間),你應該使用一個HashSet:

var hashset = new HashSet<string>(list2); 
var unwantedColIndexes = list1 
    .Select((item, idx) => new { item, idx }) // capture the original index 
    .Where(i => !hashset.Contains(i.item))  // filter using the hashset 
    .Select(i => i.idx)      // get the index only 
    .ToList(); 
0

這是一個簡單的方法:

IEnumerable<int> indexOfUnwantedColumns = list1 
    .Select((str, index) => new {str, index}) 
    .Where(x => !list2.Contains(x.str)) 
    .Select(x => x.index); 

一個更有效的方法大序列使用Enumerable.Join(「左外部聯接」):

var l1Cols = list1.Select((str, index) => new {str, index}); 
var l2Cols = list2.Select((str, index) => new {str, index}); 
IEnumerable<int> indexOfUnwantedColumns = 
      from c1 in l1Cols 
      join c2 in l2Cols on c1.str equals c2.str into gj 
      from outerJoin in gj.DefaultIfEmpty() 
      where outerJoin == null 
      select c1.index;