2

Linqを使用する方法またはより効率的な方法があるかどうかを知りたいです。whileループを使用する代わりに、Linqクエリを使用してどこで選択を実行することは可能ですか?

  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));

            }

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


    }

ありがとう!

4

3 に答える 3

1

で使用できない理由は、がジェネリックバージョンのみのメソッドである場合に、非ジェネリックを実装しているためWhere()です。を使用して、をジェネリックに変換できます。PropertyCollectionIEnumerableWhere()PropertyCollectionIEnumerableCast<T>()

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));
}

この方法は間違いなくこれ以上効率的です。

于 2012-08-27T23:55:10.383 に答える
0

これを試して:

        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

        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));
          });
于 2012-08-27T23:51:23.893 に答える
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();

これで、Keyを使用してプロパティを直接簡単に照会できます。合体および安全なナビゲーション演算子を使用すると、デフォルトで空の文字列などを使用できます。

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

「adUser」オブジェクトはUserPrincipalオブジェクトであることに注意してください。

于 2016-10-21T04:53:32.953 に答える