C#
을 사용하면 List<string>
에 어떻게 추가 할 수 있습니까? 두 개의 별도 SQL 쿼리를 실행하고 두 결과를 내 List<string>
에 저장하려고합니다. 첫 번째 쿼리는목록에 추가 <string>
빌 조
를 반환하고 두 번째 쿼리는
제임스와 찰스
하지만 내 Console.WriteLine()
만을 생산을 반환 Bill
및 Joe
이 작업을 수행하기 위해 구문에서 부적절하게 설정 한 내용은 무엇입니까?
public static List<string> tempList = new List<string>();
static void Main(string[] args)
{
string qs = "Select Top 2 firstname from thistable";
//
GetFirstSetOfData(qs);
string bc = "Select Top 2 firstname from thattable";
//
GetFirstSetOfData(bc);
foreach (string tumble in tempList)
Console.WriteLine(tumble);
}
private static void GetFirstSetOfData(string query)
{
connection = new SqlConnection(ConnectionString);
{
cmd = new SqlCommand(queryString, connection);
connection.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
tempList.Add(reader.GetValue(0).ToString());
reader.Close();
}
}
'GetFirstSetOfData'가 tempList에 접근 할 수 없으므로 컴파일되지 않습니다. 실제 코드에서'tempList'는 어떻게 정의되어 있습니까? –
죄송합니다. 클래스 변수입니다. 나 진짜 빨리 고쳐 줄게. –
감사합니다. 코드가 의미하는 것처럼 이것이 작동해야합니다. 'tempList'는 한번만 인스턴스화되고 참조 유형이기 때문에 GetFirstSetOfData에 대한 호출은 모두 같은 목록 인스턴스에 추가됩니다. 이것은'thattable'이 당신이 생각하는 결과를 실제로 리턴한다고 가정합니다. 'while (reader.Read()) {var x = reader.GetValue (0) .ToString(); Console.WriteLine (x); tempList.Add (x); }'쿼리가 예상 한 것을 반환하는지 확인합니다. –