【问题标题】:C# Linq from DataTable来自 DataTable 的 C# Linq
【发布时间】:2017-01-19 19:10:21
【问题描述】:

我有一个小的DataTable,其中包含一些我正在对其运行 LINQ 查询的行。

我无法让 LINQ 显示数据表中的文本。

当我运行它时,我可以获得列名。

我尝试了很多不同的方法,但都无济于事。

代码如下:

DataTable DTGetNarratives = DAL.GetNarrativeList();

var SelectedNarrative = 
    from n in DTGetNarratives.AsEnumerable()
    where n.Field<string>("narr_code").Equals(ClsPublic.NarrativeCode)
    select n;

foreach (var item in SelectedNarrative)
{
    //test1.Add(item.Table.Columns[col].ToString());
    //col++;

    txtLine1.Text = item.Table.Columns[0].DefaultValue.ToString();
}

在这方面的任何帮助都会很棒。

【问题讨论】:

  • 您打算使用哪个控件来显示?您可以将绑定直接设置为“SelectedNarrative”,也可以将绑定 (+=) 附加到 TextBox。

标签: c# linq datatable


【解决方案1】:

所以你有一个TextBox,但有一个IEnumerable&lt;DataRow&gt;。你期望单行吗?如果没有,你想如何在一个文本框中显示多条记录?

你可以用逗号分隔它们:

var allNarrCode = SelectedNarrative.Select(r => r.Field<string>("narr_code"));
txtLine1.text = string.Join(",", allNarrCode); 

或作为多行 TextBox 使用 Lines 属性:

txtLine1.Lines = allNarrCode.ToArray();

只有第一个:

txtLine1.Text = SelectedNarrative.FirstOrDefault();

没有 LINQ:

foreach (DataRow row in SelectedNarrative)
{
   string code = row.Field<string>("narr_code")
   // the next line is pointless since you're overwriting the text on every row
   //txtLine1.Text = code;
}

【讨论】:

    【解决方案2】:

    您可以使用Field 扩展方法,例如:

    foreach (var item in SelectedNarrative)
    {
       txtLine1.Text = item.Field<string>("narr_code"); //here
    }
    

    (可以在方法参数中指定列名)

    我不确定您是否真的需要它,因为您的 TextBox 将填充最后一行的值。

    要在单个文本框中显示所有值,您可以这样做:

    txtLine1.Text = string.Join(" ",SelectedNarrative.Select(r=> r.Field<string>("narr_code")));
    

    或者你可以这样做

    StringBuilder sb = new StringBuilder();
    foreach (var item in SelectedNarrative)
    {
      sb.Append(item.Field<string>("narr_code"));
    }
    txtLine1.Text = sb.ToString();
    

    【讨论】:

    • 但是 OP 已经在查询中使用了它,并且您总是在循环中覆盖文本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多