2012-03-29 31 views
6

Vì vậy, tôi có một danh sách với các đối tượng Materiel. Trong Materiel tôi có 15 phương thức get và set. Tôi muốn xây dựng một phương thức tìm kiếm lặp lại tất cả các đối tượng trong danh sách và tất cả các biến trong mỗi đối tượng Materiel. Phần lặp là đủ dễ dàng, nhưng tôi đang đấu tranh với chuỗi chứa-một phần. Cụm từ tìm kiếm có thể là "acto", và tôi sẽ nhận được một hit cho "Tractor". Tôi đã thử sử dụng chuỗi-Chứa lớp học, nhưng theo như tôi có thể tìm ra, nó chỉ kiểm tra chuỗi bắt đầu ở vị trí 0. Vì vậy, "Tra" được một hit, nhưng không phải "acto".C# chứa một phần của chuỗi

Có bản dựng nào trong lớp học hay tôi nên tự mình lập trình?

Xin lỗi vì lời giải thích tồi.

Mã của tôi. Tôi thấy bây giờ mà tôi nhận được số truy cập cho các chuỗi con, mà còn kết quả khác :)

protected void Button_search_Click(object sender, EventArgs e) 
    { 
     string searchTerm = TextBox1.Text.ToString().ToLower(); 

     TableRow row; 
     TableCell cell; 

     int rowNumber = 1; 

     foreach (Materiell mat in allItems) 
     { 
      if (searchTerm.Contains(mat.itemID.ToString().ToLower()) || 
       searchTerm.Contains(mat.manufacturer.ToLower()) || 
       searchTerm.Contains(mat.model.ToLower()) || 
       searchTerm.Contains(mat.serialNo.ToLower()) || 
       searchTerm.Contains(mat.dateProd.ToString().ToLower()) || 
       searchTerm.Contains(mat.location.ToLower()) || 
       searchTerm.Contains(mat.mainCategory.ToLower()) || 
       searchTerm.Contains(mat.subCategory.ToLower()) || 
       searchTerm.Contains(mat.dateAcquired.ToString().ToLower()) || 
       searchTerm.Contains(mat.price.ToString().ToLower()) || 
       searchTerm.Contains(mat.ownerID.ToString().ToLower()) || 
       searchTerm.Contains(mat.extra.ToString().ToLower()) || 
       searchTerm.Contains(mat.textComment.ToLower()) || 
       searchTerm.Contains(mat.active.ToString().ToLower())) 
      { 
       row = new TableRow(); 
       row.ID = "row" + rowNumber.ToString(); 
       rowNumber++; 

       cell = new TableCell(); 
       cell.Text = "<a href=\"#\" class=\"opendiv\">" + mat.itemID.ToString() + "</a>"; 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.manufacturer.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.model.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.serialNo.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.dateProd.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.location.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.mainCategory.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.subCategory.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.dateAcquired.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.price.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.ownerID.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.extra.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.ownDefData.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.textComment.ToString(); 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       cell.Text = mat.active.ToString(); 
       row.Cells.Add(cell); 

       Table1.Rows.Add(row); 
      } 
     } 
    } 
+2

Bạn có thể đăng một đoạn mã vì theo các tài liệu "Acto" nên đánh vào "Tractor": http://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.100).aspx – LexyStardust

+2

'" Tractor ".Contains (" acto ")' phải trả về 'true'. Bạn có thể muốn đăng một số mã của mình để chúng tôi có thể xem những gì bạn đã thử cho đến thời điểm này và nơi bạn có thể gặp sự cố. – Rawling

+0

Gah. Không có câu trả lời nào giải quyết vấn đề. Nhìn vào Lucene.NET, có thể (bạn dường như đang tìm kiếm toàn bộ tìm kiếm/lập chỉ mục; đây có phải là ứng dụng kiểu thư viện không?) – sehe

Trả lời

11

"some string".Contains("str") sẽ trả về đúng sự thật, bạn có gặp vấn đề với trường hợp mẫn không?

Nếu vậy bạn có thể sử dụng này:

public static bool Contains(this string source, string toCheck, StringComparison comp) { 
    return source.IndexOf(toCheck, comp) >= 0; 
} 

string title = "STRING"; 
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase); 

(Trích từ Case insensitive 'Contains(string)')

+1

Phương pháp mở rộng nhỏ gọn. Hãy xem xét rằng một bị đánh cắp! – LexyStardust

+0

Right ... Phương thức 'IndexOf' có phương thức' StringComparison' mà phương thức 'Contains' thiếu, không nghĩ về điều đó. Đó là tốt hơn so với sử dụng 'ToUpper' trước khi kiểm tra. Ngay lập tức kết hợp vào dự án mà tôi hiện đang làm việc. :) – Guffa

+0

OMG. Đáng ngạc nhiên, điều này đã được chấp nhận là câu trả lời. Vâng, trong trường hợp bạn muốn tìm kiếm toàn văn thực sự, hãy xem tại đây: http://stackoverflow.com/questions/9923158/c-sharp-contains-part-of-string/9924084#9924084 – sehe

3

Sử dụng IndexOf

string searchWithinThis = "ABCDEFGHIJKLMNOP"; 
string searchForThis = "DEF"; 
int firstCharacter = searchWithinThis.IndexOf(searchForThis); 

Console.WriteLine("First occurrence: {0}", firstCharacter); 

nếu chuỗi không được tìm thấy, nó sẽ trả về -1. Rất hữu ích của nó cũng biết nơi abouts chuỗi được tìm thấy.

+0

Thực ra anh ta đã làm. Phương thức 'String.Contains' chỉ gọi' IndexOf'. – Guffa

0

Phương pháp string.Contains không tìm kiếm các chuỗi con bất cứ nơi nào trong chuỗi.

"asdf".Contains("as") --> True 
"asdf".Contains("sd") --> True 
"asdf".Contains("df") --> True 
"asdf".Contains("xy") --> False 

Tuy nhiên Việc so sánh là trường hợp sensetive, vì vậy bạn có thể cần phải chuyển đổi trường hợp nếu bạn muốn thực hiện một trường hợp tìm kiếm insesetive:

"Asdf".Contains("as") --> False 
"Asdf".Contains("As") --> True 

"Asdf".ToUpper().Contains("as".ToUpper()) --> True 
1
class SearchInString 
{ 
    static void Main() 
    { 
     string strn= "A great things are happen with great humans."; 
     System.Console.WriteLine("'{0}'",strn); 

     bool case1= strn.StartsWith("A great"); 
     System.Console.WriteLine("starts with 'A great'? {0}", case1); 

     bool case2= strn.StartsWith("A great", System.StringComparison.OrdinalIgnoreCase); 
     System.Console.WriteLine("starts with 'A great'? {0} (ignoring case)", case2); 

     bool case3= strn.EndsWith("."); 
     System.Console.WriteLine("ends with '.'? {0}", case3); 

     int start= strn.IndexOf("great"); 
     int end= strn.LastIndexOf("great"); 
     string strn2 = strn.Substring(start, end- start); 
     System.Console.WriteLine("between two 'great' words: '{0}'", strn2); 
    } 
} 
2

Đối shits và tiếng cười khúc khích Tôi nghĩ đó là một dự án ăn trưa-nghỉ ngơi tốt đẹp để đưa ra một giải pháp đơn giản, nhưng 'thanh lịch' cho Câu hỏi (như tôi đã hiểu nó :)):

Ví dụ:

// I made up a Material class for testing: 
public class Materiel 
{ 
    public string A { get; set; } 
    public int B { get; set; } 
    public DateTime? C { get; set; } 
    public string D { get; set; } 
    public Nested E { get; set; } 
}  

// [...] usage: 

foreach (var pattern in new[]{ "World" , "dick", "Dick", "ick", "2012", "Attach" }) 
    Console.WriteLine("{0} records match '{1}'", Database.Search(pattern).Count(), pattern); 

Đầu ra:

2 records match 'World' 
1 records match 'dick' 
1 records match 'Dick' 
2 records match 'ick' 
1 records match '2012' 
2 records match 'Attach' 

Mã này cũng hỗ trợ

  • regex phù hợp
  • bất kỳ loại tài sản (ví dụDateTimes nullable hoặc các lớp lồng nhau)
  • thấy bất động sản phù hợp mô hình/chuỗi

Thưởng thức:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Reflection; 
using System.Text.RegularExpressions; 

namespace AClient 
{ 
    public class Materiel 
    { 
     public string A { get; set; } 
     public int B { get; set; } 
     public DateTime? C { get; set; } 
     public string D { get; set; } 
     public Nested E { get; set; } 
    } 

    public struct Nested 
    { 
     public string Data { get; set; } 
     public override string ToString() { return string.Format("Extra: {0}", Data); } 
    } 


    public static class FullText 
    { 
     public class PropMatched<T> { public PropertyInfo Property; public T Item; } 

     public static IEnumerable<PropMatched<T> > ByProperty<T>(this IEnumerable<T> items, string substr) 
     { 
      return items.ByProperty(new Regex(Regex.Escape(substr), RegexOptions.IgnoreCase)); 
     } 

     public static IEnumerable<PropMatched<T> > ByProperty<T>(this IEnumerable<T> items, Regex pattern) 
     { 
      return items.Select(i => i.MatchingProperties(pattern)).Where(m => null != m); 
     } 

     public static IEnumerable<T> Search<T>(this IEnumerable<T> items, string substr) 
     { 
      return items.Search(new Regex(Regex.Escape(substr), RegexOptions.IgnoreCase)); 
     } 

     public static IEnumerable<T> Search<T>(this IEnumerable<T> items, Regex pattern) 
     { 
      return items.Where(i => null != i.MatchingProperties(pattern)); 
     } 

     public static PropMatched<T> MatchingProperties<T>(this T item, Regex pattern) 
     { 
      if (null == pattern || null == item) return null; 

      var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance); 
      var matches = from prop in properties 
          let val = prop.GetGetMethod(true).Invoke(item, new object[]{}) 
          where pattern.IsMatch((val??"").ToString()) 
          select prop; 

      var found = matches.FirstOrDefault(); 
      return found == null ? null : new PropMatched<T> {Item = item, Property = found}; 
     } 
    } 

    class Client 
    { 
     private static readonly IEnumerable<Materiel> Database = new List<Materiel> 
      { 
       new Materiel { 
         A = "Hello", B = 1, C = null, D = "World", 
         E = new Nested {Data = "Attachment"} 
        }, 
       new Materiel { 
         A = "Transfigured", B = 2, C = null, D = "Nights", 
         E = new Nested {Data = "Schoenberg"} 
        }, 
       new Materiel { 
         A = "Moby", B = 3, C = null, D = "Dick", 
         E = new Nested {Data = "Biographic"} 
        }, 
       new Materiel { 
         A = "Prick", B = 4, C = DateTime.Today, D = "World", 
         E = new Nested {Data = "Attachment"} 
        }, 
       new Materiel { 
         A = "Oh Noes", B = 2, C = null, D = "Nights", 
         E = new Nested {Data = "Schoenberg"} 
        }, 
      }; 


     static void Main() 
     { 
      foreach (var pattern in new[]{ "World" , "dick", "Dick", "ick", "2012", "Attach" }) 
       Console.WriteLine("{0} records match '{1}'", Database.Search(pattern).Count(), pattern); 

      // regex sample: 
      var regex = new Regex(@"N\w+s", RegexOptions.IgnoreCase); 

      Console.WriteLine(@"{0} records match regular expression 'N\w+s'", Database.Search(regex).Count()); 

      // with context info: 
      foreach (var contextMatch in Database.ByProperty(regex)) 
      { 
       Console.WriteLine("1 match of regex in propery {0} with value '{1}'", 
        contextMatch.Property.Name, contextMatch.Property.GetGetMethod().Invoke(contextMatch.Item, new object[0])); 

      } 
     } 
    } 
} 
+0

Xem trực tiếp tại đây: ** [ http://ideone.com/UWgQe](http://ideone.com/UWgQe)** – sehe

Các vấn đề liên quan