2016-11-03 79 views
1

我有2個物品清單;通過使用linq比較兩個列表進行排序?

IEnumerable<Investigator> investigators = RepositoryContext.InvestigatorRep.GetInvestigators(site.Site.Id, out totalCount); 

var NewInvestigators = base.ActivePage.Investigators; 

我有30項在調查員和20項在NewInvesigators,都有屬性Id,InvId我需要匹配。

 var all = investigators.Where(b => crInvestigators.Any(a => a.InvestigatorId == b.Id)); 

我嘗試這樣做但不工作的 我想創建基於這兩個列表的匹配ID的新名單。如果Id匹配得到特定調查員(基本上是根據NewInvesigators中存在的Id調查員)。

我可以使用每個做,但我想知道是否有可能與linq

in newinvestigator我有兩個屬性的對象,investigatorId和Name。

調查員我有財產ID,城市,國家。 否調查員名單中的姓名或研究員ID。

+0

是使用淳佳n in linq –

+1

[LINQ查詢以查找列表中的項目是否包含在另一個列表中]的可能重複(http://stackoverflow.com/questions/12656582/linq-query-to-find-if-items-in-一個列表,被包含的功能於另一個列表) –

+0

有可能使用LINQ很明顯。用加入 – Viplock

回答

2

你可以嘗試這樣的事:

var result = investigators.Where(inv=>NewInvestigators.Any(ninv=>ninv.id == inv.investigatorId)) 
          .OrderBy(inv=>inv.id); 

另一種方式來獲得相同的結果是使用join

var result = from inv in investigators 
      join ninv in NewInvestigators 
      on inv.id equals ninv.investigatorId 
      order by inv.id 
      select inv; 
+0

@Downvoter我會感謝您downvote的推理。先謝謝你。 – Christos

+0

解決方案是正確的,所以我沒有看到有人會投票的原因,只有我看到的是OP也在尋找排序,並且這個解決方案將具有O(N^2)時間複雜度,這可以改進。 –

+0

@MrinalKamboj謝謝。我也添加了排序。 – Christos

0

//從NewInvestigator列表的Hashset創建如下:

HashSet<int> newInvestigatorHashset = 
     new HashSet<int>(newInvestigators.Select(element => element.NewInvestigatorId)); 

//取得共同調查baesd以上

var commonInvestigatorList = 
    investigators.Where(element => newInvestigatorHashset.Contains(element.Id)); 

//訂單研究者創造了IDS的Hashset的數據

var result = commonInvestigatorList.OrderBy(i => i.Id); 
+0

我沒有這兩個列表中的確切數據,只是在調查員身上想到我有Id,在新調查員中我有InvestigatorId。我需要匹配和排序。 –

+0

有選項,可以你只需轉換'NewInvestigators'成'Investigator',使用LINQ轉換,然後提供一個'IEqualityComparer',讓我修改我的代碼 –

+0

這是不可能的newinvestigator我有它有兩個屬性對象,調查員姓名。 在調查員我有財產Id,城市,國家。 否調查員名單中的姓名或調查員姓名。 –