如何在c#中返回数据表和整数

时间:2015-07-28 11:54:20

标签: c# datatable

我正在创建一个返回datatableint值的方法。我创建了一个只返回datatable的方法。请查看代码

    public static  DataTable ShutterstockSearchResults(string url)
    { 

       int TotalCont=0;

        DataTable dt = new DataTable();
        try
        {
            //intigration using Basic Aouth with authrization headers

            var request = (HttpWebRequest)WebRequest.Create(url);
            var username = "SC";
            var password = "SK";
            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
            request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
            request.UserAgent = "MyApp 1.0";
            var response = (HttpWebResponse)request.GetResponse();
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                var objText = reader.ReadToEnd();
                SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
               TotalCount = myojb.total_count;          

                dt.Columns.Add("Id");
                dt.Columns.Add("Discription");
                dt.Columns.Add("Small_Thumb_URl");
                dt.Columns.Add("Large_Thumb_URL");
                dt.Columns.Add("Prieview_URL");
                dt.Columns.Add("ContributorID");
                dt.Columns.Add("aspect");
                dt.Columns.Add("image_type");
                dt.Columns.Add("is_illustration");
                dt.Columns.Add("media_type");
                foreach (var item in myojb.data)
                {
                    var row = dt.NewRow();
                    row["ID"] = item.id;
                    row["Discription"] = item.description;
                    row["Small_Thumb_URl"] = item.assets.small_thumb.url;
                    row["Large_Thumb_URL"] = item.assets.large_thumb.url;
                    row["Prieview_URL"] = item.assets.preview.url;
                    row["ContributorID"] = item.contributor.id;
                    row["aspect"] = item.aspect;
                    row["image_type"] = item.image_type;
                    row["is_illustration"] = item.is_illustration;
                    row["media_type"] = item.media_type;
                    dt.Rows.Add(row);
                }
                // List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
                // Response.Write(reader.ReadToEnd());
            }          

        }

        catch (WebException ea)
        {

            Console.WriteLine(ea.Message);
            using (var stream = ea.Response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        }

        return dt;

    }

我想返回datatableTotalCont。请帮助

5 个答案:

答案 0 :(得分:5)

一般来说,一种方法只能返回一种类型。

您有两种选择:

1)创建一个具有DataTableint字段的类,例如:

public class MyReturnType
{
     public DataTable TheDataTable {get; set;}
     public int TotalCount {get; set;}
}

从你的方法中返回这个类型。

2)您可以在方法中添加out参数:

public static  DataTable ShutterstockSearchResults(string url, out totalCount)

并在您的方法中指定totalCount

答案 1 :(得分:2)

    public static Tuple<DataTable, int> ShutterstockSearchResults(string url)
    {
        [...]
        return new Tuple<DataTable, int>(dt, totalCount);
    }

    public static void SomeConsumerMethod()
    {
        var result = ShutterstockSearchResults(myPath);
        DataTable dt = result.Item1;
        int totalCount = result.Item2;
    }

答案 2 :(得分:1)

回答克劳斯的评论回答:

    public class MyReturnType
    {
         public DataTable TheDataTable {get; set;}
         public int TotalCount {get; set;}
    }

并在您的方法中:

public static  MyReturnType ShutterstockSearchResults(string url)
    { 
       MyReturnType result=new MyReturnType();
       int TotalCont=0;

        DataTable dt = new DataTable();
        try
        {
            //intigration using Basic Aouth with authrization headers

            var request = (HttpWebRequest)WebRequest.Create(url);
            var username = "SC";
            var password = "SK";
            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
            request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
            request.UserAgent = "MyApp 1.0";
            var response = (HttpWebResponse)request.GetResponse();
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                var objText = reader.ReadToEnd();
                SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
               TotalCount = myojb.total_count;          

                dt.Columns.Add("Id");
                dt.Columns.Add("Discription");
                dt.Columns.Add("Small_Thumb_URl");
                dt.Columns.Add("Large_Thumb_URL");
                dt.Columns.Add("Prieview_URL");
                dt.Columns.Add("ContributorID");
                dt.Columns.Add("aspect");
                dt.Columns.Add("image_type");
                dt.Columns.Add("is_illustration");
                dt.Columns.Add("media_type");
                foreach (var item in myojb.data)
                {
                    var row = dt.NewRow();
                    row["ID"] = item.id;
                    row["Discription"] = item.description;
                    row["Small_Thumb_URl"] = item.assets.small_thumb.url;
                    row["Large_Thumb_URL"] = item.assets.large_thumb.url;
                    row["Prieview_URL"] = item.assets.preview.url;
                    row["ContributorID"] = item.contributor.id;
                    row["aspect"] = item.aspect;
                    row["image_type"] = item.image_type;
                    row["is_illustration"] = item.is_illustration;
                    row["media_type"] = item.media_type;
                    dt.Rows.Add(row);
                }
                // List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
                // Response.Write(reader.ReadToEnd());
            }          

        }

        catch (WebException ea)
        {

            Console.WriteLine(ea.Message);
            using (var stream = ea.Response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        }

        result.TheDataTable=dt;
        result.TotalCount=TotalCount;
        return result:

    }

答案 3 :(得分:0)

如果要“返回”多个值,则您的方法需要额外的out参数。只需将所需类型的未初始化变量传递给您的方法,并将该变量分配到其中。

public void Test()
{
    int i;
    DataTable ShutterstockSearchResults("Some string", out i);
}

您的ShutterstockSearchResults方法需要相应修改:

public static DataTable ShutterstockSearchResults(string url, out int outParam)
{
    outParam = 10;

    // do other stuff
}

如果您未在outParam内进一步更改ShutterstockSearchResults,则在返回Test后其值将为10。

答案 4 :(得分:0)

您可以使用元组完成此操作。请考虑以下简单示例:

public class EmptyClass
{
    public static void Main(){
        EmptyClass something = new EmptyClass ();

        Tuple<String, int> tuple = something.returnMe ();

        Console.WriteLine ("Item 1: " + tuple.Item1);
        Console.WriteLine ("Item 2: " + tuple.Item2);
    }

    public EmptyClass ()
    {
    }

    public Tuple<String, int> returnMe() {
        return Tuple.Create ("Hello", 2);
    }
}