Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.80/5: Рейтинг темы: голосов - 5, средняя оценка - 4.80
2 / 2 / 1
Регистрация: 26.06.2015
Сообщений: 56
1

Поиск по строке (с применением индексатора)

27.06.2016, 16:44. Показов 987. Ответов 3
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый день,

Хочу, помимо всего прочего реализовать поиск по названию модели с применением индексатора, но так чтобы получить все возможные вхождения. Пока получается найти только первое (328 строка).

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
using System;
 
abstract class Device
{
    protected Double price;
    protected String vendor;
    protected String category;
    protected DateTime productionDate;
    protected Byte warranty;
    protected String model;
 
    public Double Price
    {
        get
        {
            return price;
        }
        set
        {
            if (price > 0) price = value;
        }
    }
 
    public String Vendor
    {
        get
        {
            return vendor;
        }
        set
        {
            vendor = value;
        }
    }
 
    public String Category
    {
        get
        {
            return category;
        }
        set
        {
            category = value;
        }
    }
 
    public DateTime ProductionDate
    {
        get
        {
            return productionDate;
        }
        set
        {
            productionDate = value;
        }
    }
 
    public Byte Warranty
    {
        get
        {
            return warranty;
        }
        set
        {
            if (warranty > 0) warranty = value;
        }
    }
 
    public String Model
    {
        get
        {
            return model;
        }
        set
        {
            model = value;
        }
    }
}
 
class Laptop : Device
{
    public Laptop(Double price, String vendor, String category, DateTime productionDate, Byte warranty, String model)
    {
        this.price = price;
        this.vendor = vendor;
        this.category = category;
        this.productionDate = productionDate;
        this.warranty = warranty;
        this.model = model;
    }
 
    public override String ToString()
    {
        return "Vendor: " + vendor + ", model: " + model + ", price: $" + price + ", date of production: " 
            + productionDate.ToShortDateString() + ", warranty: " + warranty + " years.";
    }
}
 
class Tablet : Device
{
    public Tablet(Double price, String vendor, String category, DateTime productionDate, Byte warranty, String model)
    {
        this.price = price;
        this.vendor = vendor;
        this.category = category;
        this.productionDate = productionDate;
        this.warranty = warranty;
        this.model = model;
    }
 
    public override String ToString()
    {
        return "Vendor: " + vendor + ", model: " + model + ", price: $" + price + ", date of production: "
            + productionDate.ToShortDateString() + ", warranty: " + warranty + " years.";
    }
}
 
class Smartphone : Device
{
    public Smartphone(Double price, String vendor, String category, DateTime productionDate, Byte warranty, String model)
    {
        this.price = price;
        this.vendor = vendor;
        this.category = category;
        this.productionDate = productionDate;
        this.warranty = warranty;
        this.model = model;
    }
 
    public override String ToString()
    {
        return "Vendor: " + vendor + ", model: " + model + ", price: $" + price + ", date of production: "
            + productionDate.ToShortDateString() + ", warranty: " + warranty + " years.";
    }
}
 
class Charger : Device
{
    public Charger(Double price, String vendor, String category, DateTime productionDate, Byte warranty, String model)
    {
        this.price = price;
        this.vendor = vendor;
        this.category = category;
        this.productionDate = productionDate;
        this.warranty = warranty;
        this.model = model;
    }
 
    public override String ToString()
    {
        return "Vendor: " + vendor + ", model: " + model + ", price: $" + price + ", date of production: "
            + productionDate.ToShortDateString() + ", warranty: " + warranty + " years.";
    }
}
 
class Case : Device
{
    public Case(Double price, String vendor, String category, DateTime productionDate, Byte warranty, String model)
    {
        this.price = price;
        this.vendor = vendor;
        this.category = category;
        this.productionDate = productionDate;
        this.warranty = warranty;
        this.model = model;
    }
 
    public override String ToString()
    {
        return "Vendor: " + vendor + ", model: " + model + ", price: $" + price + ", date of production: "
            + productionDate.ToShortDateString() + ", warranty: " + warranty + " years.";
    }
}
 
//////////////////////////////////////////////////////////////////////////////////////
 
class Store
{
    private Device[] devices;
 
    public Store(int size)
    {
        devices = new Device[size];
    }
 
    public int Length
    {
        get
        {
            return devices.Length;
        }
    }
 
    public Device this[int index]
    {
        get
        {
            if (index < 0 || index >= devices.Length)
            {
                throw new IndexOutOfRangeException();
            }
            else
            {
                return devices[index];
            }
        }
        set
        {
            devices[index] = value;
        }
    }
 
    public Device this[Double price]
    {
        get
        {
            if (price <= 0.0)
            {
                throw new IndexOutOfRangeException();
            }
 
            return this[FindByPrice(price)];
        }
    }
 
    public Device this[String name]
    {
        get
        {
            if (name.Length == 0)
            {
                //return null;
                throw new IndexOutOfRangeException();
            }
 
            return this[FindByName(name)];
        }
    }
 
    private Int32 FindByName(String name)
    {
        Int32 result = -1;
 
        for (int i = 0; i < devices.Length; i++)
        {
            if (devices[i].Vendor == name)
            {
                result = i;
                break;
            }
        }
 
        return result;
    }
 
    public Int32 FindByPrice(Double price)
    {
        Int32 result = -1;
 
        for (Int32 i = 0; i < devices.Length; i++)
        {
            if (devices[i].Price == price)
            {
                result = i;
                break;
            }
        }
 
        return result;
    }
 
    public Int32[] FindByPrice(Double priceFrom, Double priceTo)
    {
        Int32 count = 0;
 
        for (Int32 i = 0; i < devices.Length; i++)
        {
            if (devices[i].Price >= priceFrom && devices[i].Price <= priceTo)
            {
                count++;
            }
        }
        Int32[] result = new Int32[count];
 
        for (Int32 i = 0, y = 0; i < devices.Length; i++)
        {
            if (devices[i].Price >= priceFrom && devices[i].Price <= priceTo)
            {
                result[y] = i;
                y++;
            }
        }
 
        return result;
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        Store s = new Store(6);
        s[0] = new Laptop(5700, "Samsung", "Laptops", DateTime.Parse("2015.11.23"), 2, "AAA");
        s[1] = new Tablet(4700.25, "Asus", "Tablets", DateTime.Parse("2016.01.01"), 1, "BBB");
        s[2] = new Smartphone(3700, "HTC", "Smartphones", DateTime.Parse("2015.10.23"), 1, "CCC");
        s[3] = new Charger(150.55, "Hiawei", "Chargers", DateTime.Parse("2016.03.17"), 1, "DDD");
        s[4] = new Case(80, "no name", "Cases", DateTime.Parse("2015.08.08"), 0, "EEE");
        s[5] = new Laptop(6700, "Samsung", "Laptops", DateTime.Parse("2016.06.23"), 2, "FFF");
 
        /*
        try
        {
            foreach(int el in s.FindByPrice(4000, 6000))
            {
                Console.WriteLine(s[el]);
            }
        }
        catch
        {
            Console.WriteLine("Ничего не найдено!");
        }*/
 
        try
        {
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == s["Samsung"]) 
                    Console.WriteLine(s[i]);
            }
        }
        catch
        {
            Console.WriteLine("Ничего не найдено!");
        }
 
        //Console.WriteLine(s["Samsung"]);
        //Console.WriteLine(s[4700.25]);
    }
}
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
27.06.2016, 16:44
Ответы с готовыми решениями:

Поиск в строковой переменной с применением регулярных выражений
Подскажите, пожалуйста, можно ли (и как) в строковых переменных (Dim stroka As String) искать с...

Создание индексатора
Не могу понять как мне создать идексатор(массив) вот кодusing System; using System.Collections; ...

Обобщенное значение из индексатора
Всем привет. Непонимаю как у индексатора изменить тип на обобщение. public virtual Card this ...

Неясность в сеттере индексатора
Всем доброго времени года! Господа товарищи, подымите мне плуг, пожалуйста, а то у самого не...

3
123 / 123 / 72
Регистрация: 11.05.2014
Сообщений: 331
27.06.2016, 17:47 2
Не знаю, насколько это концептуально правильно, но если через индексатор, то можно попробовать так:

Сам индексатор:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
public IEnumerable<Device> this[String name]
    {
        get
        {
            if (name.Length == 0)
            {
                //return null;
                throw new IndexOutOfRangeException();
            }
 
            return devices.Where(x => x.Vendor == name);
        }
    }
Вызов:
C#
1
2
3
            foreach (Device dev in s["Samsung"]) {
                Console.WriteLine(dev);
            }
2
2 / 2 / 1
Регистрация: 26.06.2015
Сообщений: 56
27.06.2016, 18:07  [ТС] 3
Спасибо, а можно без лямбды, а то мы это "ещё не проходили" ))
0
123 / 123 / 72
Регистрация: 11.05.2014
Сообщений: 331
27.06.2016, 18:21 4
Лучший ответ Сообщение было отмечено petuz как решение

Решение

Тогда можно попробовать так:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public IEnumerable<Device> this[String name]
    {
        get
        {
            if (name.Length == 0)
            {
                //return null;
                throw new IndexOutOfRangeException();
            }
 
            //return devices.Where(x => x.Vendor == name);
            return FindByName(name);
        }
    }
 
    private IEnumerable<Device> FindByName(String name)
    {
        foreach (Device dev in devices) {
            if (dev.Vendor == name) {
                yield return dev;
            }
        }
    }
2
27.06.2016, 18:21
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
27.06.2016, 18:21
Помогаю со студенческими работами здесь

Подсчитать количество вхождений буквы «о» в строке «прямой поиск в текстовой строке»
Подсчитать количество вхождений буквы «о» в строке «прямой поиск в текстовой строке» Заменить в...

Работа с массивами. Поиск наименьшего числа в строке и наибольшего в строке
Добрый вечер. Надо найти наименьшее число в строке и наибольшее в столбце. Примерно вот так...

Ввести с клавиатуры строку. Найти шаблон во введенной строке (поиск подстроки в строке)
Помогите написать программу. Ввести с клавиатуры строку. Ввести с клавиатуры коротенькую строку -...

Операции в строке: поиск, замена, удаление символа в строке
Доброго здравия! В ассемблере совсем новичок, поэтому прошу помощи. Программа должна получать...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru