访问foreach循环外部的变量

时间:2021-10-05 00:23:43

How do I go about accessing a variable outside a loop? The code below doesn't seem to work, the variable is empty.

如何访问循环外的变量?下面的代码似乎不起作用,变量是空的。

var userID;
foreach(var row in db.Query("SELECT ProviderUserId FROM webpages_OAuthMembership WHERE UserID = @0", currentUserId))
{
    userID = row.ProviderUserId;

}  
var userID1 = userID;

2 个解决方案

#1


2  

Which iteration do you want the value from? The first? The last? What should happen if there are no results?

您希望从哪个迭代中获取值?首先?最后?如果没有结果会怎么样?

LINQ is probably a simpler approach here:

LINQ可能是一个更简单的方法:

string sql = "SELECT ProviderUserId FROM webpages_OAuthMembership WHERE UserID = @0";
var userId = db.Query(sql, currentUserId)
               .Select(x => x.ProviderUserId)
               .SingleOrDefault();
if (userId != null)
{
    ...
}

(Of course that won't work as-is if ProviderUserId isn't a nullable type of some kind, but we don't really have much information at the moment...)

(当然,如果ProviderUserId不是某种类型的可空类型,那将无法正常工作,但我们目前并没有太多信息...)

#2


0  

your foreach loop return IEnumerable collection

你的foreach循环返回IEnumerable集合

var userID;
foreach(var row in db.Query("SELECT ProviderUserId FROM webpages_OAuthMembership WHERE UserID = @0", currentUserId))
{
    userID = row.ProviderUserId;

}  
var userID1 = userID;

for holding userID you can do this

对于持有userID,您可以执行此操作

List<string> userIDs = new List<string>();
foreach(var row in db.Query("SELECT ProviderUserId FROM webpages_OAuthMembership WHERE UserID = @0", currentUserId))
{
    userIDs.Add( row.ProviderUserId);

}  
//Now You have items in userIDs List

#1


2  

Which iteration do you want the value from? The first? The last? What should happen if there are no results?

您希望从哪个迭代中获取值?首先?最后?如果没有结果会怎么样?

LINQ is probably a simpler approach here:

LINQ可能是一个更简单的方法:

string sql = "SELECT ProviderUserId FROM webpages_OAuthMembership WHERE UserID = @0";
var userId = db.Query(sql, currentUserId)
               .Select(x => x.ProviderUserId)
               .SingleOrDefault();
if (userId != null)
{
    ...
}

(Of course that won't work as-is if ProviderUserId isn't a nullable type of some kind, but we don't really have much information at the moment...)

(当然,如果ProviderUserId不是某种类型的可空类型,那将无法正常工作,但我们目前并没有太多信息...)

#2


0  

your foreach loop return IEnumerable collection

你的foreach循环返回IEnumerable集合

var userID;
foreach(var row in db.Query("SELECT ProviderUserId FROM webpages_OAuthMembership WHERE UserID = @0", currentUserId))
{
    userID = row.ProviderUserId;

}  
var userID1 = userID;

for holding userID you can do this

对于持有userID,您可以执行此操作

List<string> userIDs = new List<string>();
foreach(var row in db.Query("SELECT ProviderUserId FROM webpages_OAuthMembership WHERE UserID = @0", currentUserId))
{
    userIDs.Add( row.ProviderUserId);

}  
//Now You have items in userIDs List