【问题标题】:Foreach String variable (not Value) in a List<>List<> 中的 Foreach 字符串变量(不是值)
【发布时间】:2018-03-29 19:21:28
【问题描述】:

获得很多关于如何在字符串列表中查找字符串值的答案。 但不是列表中的字符串类型,然后查询那些字符串。我正在尝试返回具有用户输入的任何字符串值的每个 Listitem,例如全局搜索。我想用 Linq,不过老派也不错。

我的研究文章底部。

我有一个车库类,其中包含许多不同变量类型的列表。

[Serializable()]
public class Garage 
{
public static BindingList<Vechicle> VechicleList = new 
BindingList<Vechicle>();

基于下面的Vechicle类:

[Serializable()]
public class Vechicle
{
//String formatting for Useraccount section and main list
private string HeaderStringFormat = "{0,-8} {1,-15} {2,-15} {3,-10:c} {4,-10} 
{5,-5} {6,-10}";
public string Make { get; set; }
public string Model { get; set; }
public string Color { get; set; }
public decimal Price { get; set; }
public double KilometerReading { get; set; }
public Image Pic { get; set; } = Properties.Resources.Default;
public bool IsSold { get; set; } = false;
public DateTime DateSold { get; set; }    

我想查询此列表中的所有字符串变量,然后通过查询字符串查询这些变量,如下所示。如果可能的话,我不想用 trycatch 浏览每一个项目。

到目前为止,这是我的代码:

  private void Txt_Search_TextChanged(object sender, EventArgs e)
    {
        string query = Txt_Search.Text.Trim();
        List<Vechicle> SearchList = new List<Vechicle>();
        foreach (Vechicle v in Garage.VechicleList.Where()
       //Stuck here unsure how to get all values of strings to then query
   }

我看过的东西,但似乎找不到答案

c# - 在列表中查找匹配项的最简洁方法 - 代码日志

foreach 列表中与字符串匹配的项目 - Google 搜索

c# - 如何在 foreach 中比较值 - 代码日志

c# - 带有 where 子句的 Foreach? - 堆栈溢出

foreach where - Google 搜索

c# - 我如何遍历一个列表并抓取每个项目? - 堆栈溢出

foreach 字符串在列表中的位置 - Google 搜索

列表的每个字符串中的每个字符串变量 - Google 搜索

foreach 列表中的字符串 - Google 搜索

foreach 字符串 - Google 搜索

c# - 在类列表中查找类元素 - 代码日志

在 c# 类中搜索字符串 - Google 搜索

在类中搜索字符串 - Google 搜索

【问题讨论】:

  • 您的意思是枚举MakeModelColor 属性,因为它们是string 的唯一属性?如果是这样,您将需要反思才能做到这一点。这种事情更适用于动态语言,而不是像 C# 这样的静态类型和编译语言。
  • 为了简化,我想重申 VechicleList 中的所有 Vechicles,并且只查询那些输入的任何文本字符串的字符串项。不会导致错误。
  • 哦,刚刚知道了.. 是的,只是字符串值。例如,如果汽车名称是 Toyota 并且用户搜索“toyota”,他们将匹配到 Vechicle 项目。但如果“Toyota”作为另一个列表项存在,请将其返回。哦,如果丰田是一种颜色,它也会回归
  • 也许这个答案可能会为您指明正确的方向? stackoverflow.com/questions/1718863/…
  • 是的,你会的。否则,您将不得不使用 @alec 建议的反射来查找字符串类型的类的所有属性。但这最终会变得更加冗长,并且只有在查询未知类型时才真正有用。正如@alec 建议的那样,只需执行Garage.VechicleList.Where(v =&gt; v.Make.Equals(query) || v.Model.Equals(query) || v.Color.Equals(query))

标签: string list linq foreach bindinglist


【解决方案1】:

谢谢大家 明确为此链接How to iterate all "public string" properties in a .net class

private string[] GetPublicStringProperties()
{
return this.GetType()
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(pi => pi.PropertyType == typeof(string))
    .Select(pi => pi.Name)
    .ToArray();
}

@Cameron Aavik :)

【讨论】:

  • 这会循环遍历属性的名称,而不是值(这是您想要的)
  • 当您已经知道字段名称时,使用反射确实是个坏主意。为什么不在非string 属性或字段上使用ToString
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
  • 2017-09-27
相关资源
最近更新 更多