Let's say I have:
List<string> sqlServerNames;
and a method:
List<string> GetDatabases( string serverName );
And I want a single query to get a list of { serverName, databaseName }
Is there a way to do this with Linq?
sqlServerNames.????
So for example, if I have two servers, ".", and "SQL2016".
And "." has "db1", "db2"
And "SQL2016" has "db3"
I'd want:
".", "db1"
".", "db2"
"SQL2016", "db3"
Probably with an anonymous type.
只需尝试如下所示:
var tuples = sqlServerNames.SelectMany(server => GetDatabases(server).Select(db => Tuple.Create(server, db))).ToList()
Recommend using another overload of SelectMany
. The other answers will need to allocate a new enumerable/enumerator/delegate for each server name, while this doesn't.
sqlServerNames.SelectMany(serverName => GetDatabases(serverName),
(serverName, databaseName) => new
{
ServerName = serverName,
DatabaseName = databaseName
});
equivalent to:
from serverName in sqlServerNames
from databaseName in GetDatabases(serverName)
select new
{
ServerName = serverName,
DatabaseName = databaseName
};
You can use SelectMany
method :
sqlServerNames
.SelectMany(sn => GetDatabases(sn)
.Select(dbn => new {
ServerName = sn,
DatabaseName = dbn
}
)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.