2012-08-27 24 views
2

我想知道是否有一種方式或更有效的方式使用Linq。而不是使用while循環,是否可以使用Linq查詢進行選擇?使用linq與PropertyValueCollection

public UserPrincipal GetUser(string sUserName, string spwd, string domain, string ou) 
    { 
     PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, domain, ou, sUserName, spwd); 


     UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName); 

     DirectoryEntry user = (DirectoryEntry)oUserPrincipal.GetUnderlyingObject(); 
     PropertyCollection pc = user.Properties; 
     IDictionaryEnumerator ide = pc.GetEnumerator(); 

     ide.Reset(); 

     while (ide.MoveNext()) 
     { 
      PropertyValueCollection pvc = ide.Entry.Value as PropertyValueCollection; 
      if (ide.Entry.Key.ToString() == "XYZ") 
      { 
       //Response.Write(string.Format("name: {0}", ide.Entry.Key.ToString())); 
       //Response.Write(string.Format("Value: {0}", pvc.Value)); 

      } 

     } 
    .......; 
    .......; 


    } 

謝謝!除了

 foreach (PropertyValueCollection pvc in pc.OfType<PropertyValueCollection>().Where(v => v.PropertyName == "XYZ")) 
     { 
      Response.Write(string.Format("name: {0}", pvc.PropertyName)); 
      Response.Write(string.Format("Value: {0}", pvc.Value)); 
     } 

,你可以嘗試使用ForEach

回答

1

你不能在一個PropertyCollection使用Where()的原因是因爲它實現了非通用IEnumerable ,當Where()是一個只有通用版本的方法。您可以使用Cast<T>()PropertyCollection轉換爲泛型IEnumerable

var matches = pc.Cast<DictionaryEntry>().Where(p => p.Key.ToString() == "XYZ"); 

foreach(var match in matches) 
{ 
    Response.Write(string.Format("name: {0}", match.Key)); 
    Response.Write(string.Format("Value: {0}", match.Value)); 
} 

這種方式懷疑是更有效率。

0

試試這個

 pc.OfType<PropertyValueCollection>() 
      .Where(v => v.PropertyName == "XYZ") 
      .ToList() 
      .ForEach(pvc => 
      { 
       Response.Write(string.Format("name: {0}", pvc.PropertyName)); 
       Response.Write(string.Format("Value: {0}", pvc.Value)); 
      }); 
0

這是一個很老的線程,但我正在尋找一種使用LINQ處理PropertyCollection的方法。我嘗試了建議的方法,但在投射到DictionaryEntry時,我總是會得到無效的轉換異常。在DictionaryEntry中,像FirstOrDefault這樣的東西很時髦。所以,我只是這樣做:

var directoryEntry = adUser.GetUnderlyingObject() as DirectoryEntry; 
directoryEntry.RefreshCache(); 
var propNames = directoryEntry.Properties.PropertyNames.Cast<string>(); 
var props = propNames 
    .Select(x => new { Key = x, Value = directoryEntry.Properties[x].Value.ToString() }) 
    .ToList(); 

有了到位,然後我就可以很容易地查詢任何直接財產密鑰。使用聚結和安全導航運營商允許默認爲空字符串或任何..

var myProp = props.FirstOrDefault(x => x.Key == "someKey"))?.Value ?? string.Empty; 

注意「ADUser便有」對象是UserPrincipal對象。